Android SQLite interaction best practice - android

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

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.

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.

Related

SQLite database as IntentService, caching database state?

The documentation for Android's SQLite interfaces mention that database accesses should be performed from an IntentService as they are potentially long-running operations, so the GUI thread should not block on them.
The IntentService is shut down as soon as no further Intents are queued for it, which would happen basically after every request, so the database handles are built up and destroyed for each query as well, which seems wasteful.
Is there a way to keep an IntentService around longer, or somehow otherwise avoid a race between the GUI thread posting more Intents and the service answering them?
Should I just make my query Intents contain a list of queries that should all be performed, or would that cause other problems with message sizes?
The documentation for Android's SQLite interfaces mention that database accesses should be performed from an IntentService as they are potentially long-running operations, so the GUI thread should not block on them.
I/O of all forms should be performed on background threads, so as not to block the main application thread. IntentService itself is not a great choice, given changes on Android 8.0+.
A more typical approach nowadays is to have database access be managed by a singleton repository (whether a manually-created singleton or a singleton supplied to you via a dependency injection framework). The repository can use any number of approaches to provide a reactive API while doing the I/O on a background thread, including:
RxJava
LiveData and ordinary threads, executors, etc.
Kotlin coroutines
If you use Room as your database access layer, it gives you all three of those options "for free". Some other ORMs offer similar capabilities.
Is there a way to keep an IntentService around longer, or somehow otherwise avoid a race between the GUI thread posting more Intents and the service answering them?
Background services can only run for one minute. If your concern is the overhead in opening the database, use a singleton repository, and only open it once per process invocation. It's also entirely possible that you do not need a service; if you have a foreground UI, a service may be pointless.
Should I just make my query Intents contain a list of queries that should all be performed...?
Um, possibly, but again, using a service here may not be necessary and definitely makes the problem more complex.
So: use a background thread for I/O. That does not have to involve a service.

Do I ALWAYS need to use AsyncTask when using MySQL?

Hi guys I have a question about Asyntask which is used in android studio :
As far as I know AynTask is used for user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished.
But let's say that I want to register an account so that I can login, that shouldnt take time at all so why should I use Asyntask for this?
Let's say I want to send 100 strings to the Database, that can be done in milisecs I think, so again, why to use and how to decide when to use Asyntask?
I hope you guys can help me out, I have been searching for a long time !
If you don't know how much time operation will take, you should perform it in a separate thread and then pass the results to UI thread. I think the database should be accessed in a separate thread as well as HTTP requests. In the case of time-consuming query, it may be a long operation. AsyncTask is one way to do it. You can also use other techniques. The popular technique used nowadays is applying RxJava library, which gives you the high-level functional reactive interface for writing multi-threaded applications with a few additional features. You can perform an operation in e.g. Sechdulers.io() (I/O) thread and then pass the result to AndroidSchedulers.mainThread(), which is UI thread.
There are also other techniques like using Looper & Handler from Android SDK or using Thread class from Java, but such techniques require more knowledge, more work, writing more boilerplate code & you have more problems to deal with.

Android - SQLite ContentResolver insert/delete/update on UI Thread?

I have looked through many examples/tutorials of using SQLite in Android. Let's say you have an app that uses SQLite, ContentProvider, CursorLoader, a custom CursorAdapter.
Now all major examples of this that I've found rely on a CursorLoader to fetch data to the CursorAdapter, which by the nature of CursorLoader happens in an Async - UI thread safe manner. However, these same examples all make insert/delete/update calls through the ContentResolver on the main thread (e.g. from onClick, onResume, onPause). (Example) They don't wrap these calls in an AsyncTask or launch a separate thread or use the AsyncQueryHandler.
Why is this, how can so many well written blogs/examples make such an obvious mistake? Or are simple single row insert/delete/update calls so quick that they are safe enough to launch from the Main/UI thread? What is the proper way to do these quick calls?
I also got confused about the samples making calls on the main thread. I guess the samples just simplified the demonstrations avoiding extra threads and callbacks, since single insert/update/delete call may return quickly.
Besides the Loader pattern for query, android did provide a helper class AsyncQueryHandler, since API level 1, for async CRUD operations with full CRUD callbacks supported. The AsyncQueryHandler works inside with a HandlerThread for the async operations and delivers the results back to the main thread.
So I do believe the ContentProvider queries should run in worker threads other than the UI, and those samples may not be best practices according to the official design.
=== edit
Found an annotation from the official framework docs, see this or this, Line 255:
In practice, this should be done in an asynchronous thread instead of
on the main thread. For more discussion, see Loaders. If you are not
just reading data but modifying it, see {#link android.content.AsyncQueryHandler}.
=== edit 2
Link to actual android dev guide containing the above quote
This question has been on my mind since a long time. I guess, this depends on the complexity of the file we are trying to Insert, Update or Delete. If our application is going to Insert or Update large files, it would be always right to do it asynchronously and if the files aren't going to be that big, running it on UI thread can be done.
However, it is always recommended to continue with Database operations on a separate thread.
I think you've answered your own question. I do believe CursorLoader extends AsyncTaskLoader. Calls made from UI thread only process the call TO the CusorLoader (which uses AsyncTask.) What is being done BY the call still does not occur on UI Thread. Making a call to a method/function that then runs things on a seperate thread is still doing work away from UI thread.
What work do you think is happening on the UI thread?
Please show Debug log if possible or example where you think work is done on UI.
It shouldn't be.
Not trying to argue just want to know how you've come to the conclusion of UI work?

Is it necessary to access an SQLiteDatabase in an AsyncTask?

Is it necessary or even good practice to always access an SQLiteDatabase from an AsyncTask?
Doing it from the UI thread seems to cause no problems and is much simpler to implement.
It is recommended to not perform IO from your main application thread, but, it does not have to be done using an AsyncTask.
You have other options for getting out of your main thread too, some of which include the Loader Framework, IntentService, and Executors.
It's good practice. Database operations aren't always quick, so Android recommends doing all database and network operations on a background thread (AsyncTask, Runnable, etc).
No, it is not necessary to ALWAYS access your database in another thread. It depends on how long it takes. Usually reads / writes are fast, do not slow down the UI, and do not require another thread. However, when performing lengthy operations like cleanups etc. then yes, it is a good idea to do them in another thread.

Which is the right way for multithreading for android

currently i am using an activity which does asyntask to retrive a list of data from a remote database.
After retrieving under the onPostExecute, i used the method to display out the information gathered from the remote database. Is this the correct way for threading? Previosuly i used a handler in the onPostexecute so that i can intersect the ui thread for displaying information
There's lots of ways to achieve multithreading in Android. If you need to perform some background operation then update the UI once this is complete, AsyncTasks are definitely the way to go. Keep in mind there is a thread limit. Look at this SO question for more information on thread limits.
AsyncTask is efficient implementation of Haldler approach . so whenever multithreading needs to interact with UI thread use AsyncTask else follow standard java threading guidelines.

Categories

Resources