Reputation: 13
Is it OK to have SQLite
interactions on UI thread ??
Is it a best practice to embed interactions with SQLite within a service(AsyncTask
or IntentService
) or should we use CursorLoader
for SQLite
??
1)If I use IntentService
to return a list of user defined objects then how do I that. Should we use BroadcastReciever
and put the list of objects in intent as ArrayList
of Parcelable
objects and send it back to UI thread.
2)If I have to use cursor Loaders then I need to write custom loader for SQLite
by extending AsyncTaskLoader
and override doInBackGround
method where I add required code.
Please suggest me which is better approach as I am new to android and also share the code if anybody has it
Upvotes: 0
Views: 453
Reputation: 161
Although you can access database on UI thread & update views straightaway. One should avoid this practice & do database access on helper threads i.e. use asynctasks/services with worker threads even if operation is taking less than 5 seconds. You can always use non-UI to UI thread communication mechanisms in android for updating views once thread is done with it's job.
Refer this link to learn basics about non-UI to UI thread communication mechanisms. http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/
I normally use AsyncTasks created on activity/service for DB access.
If android later decides to disallow DB access on UI thread, then your code will not need rework if DB access already on non-UI thread.
There is history with android that network access was earlier allowed on UI thread, but now if you set targetSDKversion=11, then application will throw NetworkOnMainThreadException & exit. Hence, it is better to DB access on non-UI thread.
Upvotes: 0
Reputation: 23665
It is perfectly fine to use SQLite on the UI Thread. There is no need to add all that service and parable stuff, except perhaps if you intend to scroll through huge amounts of data.
Upvotes: 2