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.
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.
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?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Handler vs AsyncTask vs Thread
Am a newbie to android and am on the way developing my first app...
Which kind of threading is better to create process separate from UI thread?
AsyncTask or extending Thread class with Handler and Message?
I have gone throug this thread..
Put an object in Handler message
The person have told that, "Oh, and I'm moving away from using AsyncTask objects, as I believe they increase code coupling too much.".
What's meant by code coupling? Should I use Java thread with Handler and Message classes or should I use Async task?
As this is going to be your first app it would be best to put this question away for a while. Instead you would want to make your application working anyhow. Doing that you will gain enough experience to decide for yourself.
Having said this AsyncTask seems to be easier to use if what you need is to do something in background and present progress and results in UI.
One real problem with either approach is that when you rotate your device your UI gets recreated. And if you store ane references to the older UI in your thread/asynctask and use them your app the crashes.
AsyncTask uses Java's native threads in the background. The advantage of using them is that you get 3 methods - onPreExecute, doInBackground & onPostExecute which make you life easier.
AsyncTask is a nice abstraction for well-defined tasks that need to be done on a worker thread (to avoid blocking the main thread), while reporting progress and publishing results to the UI. Examples of such tasks are : downloading file from internet, calling a webservice, querying the database etc. It maintains a pool a worker threads to run these tasks. Using AsyncTask frees you from having to write code to create and mange threads and to dispatch UI updates to the UI thread.
AsyncTask is not appropriate when the background task is an ongoing process rather than a well-defined task. Examples : playing music, continuously tracking location, continuously downloading news feeds etc. In such cases, it is appropriate to create and manage a separate thread.
This question comes from an issue I am having, or really confusion on something. So its frowned upon to query databases on the UI thread. But my issue is, what if what appears on the screen relies on what the result is. Should you still run it in the background, or should you halt the screens output until you know the info you need from the database?
The way you should set it up is to use an AsyncTask to query the database, using the doInBackground method. Then use the onPostExecute method to update the UI. You can't update the UI on any other thread than the main thread.
Hope that makes sense. If not, here are a couple articles that might help:
http://android-developers.blogspot.com/2009/05/painless-threading.html
http://developer.android.com/reference/android/os/AsyncTask.html
http://www.peachpit.com/articles/article.aspx?p=1823692&seqNum=3
Best of luck!