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.
Related
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.
As I understood, Firebase Database performs all the reading tasks on a single thread.
Is there a way to split that work into few different threads?
Is there a way to make a tasks execute before another? some parallel to handler.postAtFrontOfQueue() ?
The Firebase client handles all network and disk I/O on a separate thread to avoid interfering with the UI of your Android app. The callbacks into your code are invoked on the main thread, so that your code can interact with the UI.
The operations are executed in the same order in which you call their APIs. There is no way to re-order operations. There is also no way to set up multiple threads, nor have I ever seen a need for that. Interacting with a remote service is inherently an I/O intensive operations, which is not helped by multi-threading.
This sounds like a XY problem. If you describe the actual problem that you're trying to solve, we may be able to help better.
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.
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?
I'm currently writing and android app, and I was using HttpClients and those classes. I spent 2 hours trying to fix some errors until I read a post that said that you cant do that operation in the main thread. So they suggested I use AsyncTask.
So My question is, how do I know which operations should be done in a different Thread? is there a list where I can read them?
Any information would be good, thanks in advance.
A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:
Opening a Socket connection (i.e. new Socket()).
HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
Attempting to connect to a remote MySQL database.
Downloading a file (i.e. Downloader.downloadFile()).
If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
The network exception is the only exception that will be thrown in android by blocking the UI-Thread. So you have to keep 3 rules in mind by programming in android.
Don't let the UI-Thread handle operations that will take more then 5 seconds to complete.
Don't let a broadcast receiver handle operations that will take more then 20 seconds to complete the onReceive ().
And don't handle network operations in the UI-Thread.
As other answers have said, Android is not thread safe, meaning:
You cannot manipulate the UI from a Background thread
You cannot do heavy tasks on the UI thread
Other operations of this sort could include processing large amounts of data/ database manipulation/HTTP requests/Network management. Really, I believe anything that doesn't require the UI thread but does involve large processing time should be moved to a seperate thread.
This makes logical sense, because if you were to do heavy processing, the user would feel a lag and User Experience would be compromised (and, ofcourse, could definitely be used to overload the system,etc.) Therefore, the system will kill the process and throw an error post-honeycomb.
As a result, you want to use an Async Task.
An Async Task really just opens a new Thread on which you can execute heavy processing or Network Connections. For Network Connections, I recommend the use of AsyncClients like this one that implement AsyncTask in an easier format for you to use. There are also libraries like UniversalImageLoader that will allow you to load Images into Grids/Lists.
I also highly reccomend you read the official Android documentation discussing this and there is a useful post on the Android blog about this as well. Lastly, I feel as if this post might be useful to you because it may include the error you encountered (Error because you performed the operation on the UI thread).
Other Resources I've found:
CommonsWare's Service
This StackOverflow Question has some good solutions.
In conclusion, here is an example of an AsyncTask being used. (nicely put answer from #Graham Smith).
Anything that takes a lot of time should be done in another thread. This includes large IO and network access. However I think only network access will throw an exception, anything else would cause an unresponsive UI. Although if you take way too long you'll trip a watchdog timer and the app will be killed.
As Gabe mentioned, you should do heavy tasks in separate threads.
there are two important things about android threads.
1 is the common threads..(the thread that do what you ask)
2 is the ui thread...(the thread that listens the user inreaction and draws ui)
you can change ui(Views act) only by ui thread.
on the other hand after honeycomb it is forbidden to do http requests in main thread.
(it is called strict mode)
in short, any operation that blocks user interaction should be done in another thread.
i hope this helps you.