Android : Calling the methods on UI thread from AsyncTask doInBackground method - android

I am using AsyncTask to upload data to UI. i wrote the code to download data from server in a separate method and i am calling that method from doinBackground. It will give error because UI methods can't access from doInBackground.but, i want to access . any alternative process is there to access the UI method from doinBackground.?

any alternative process is there to access the UI method from doinBackground.?
Call publishProgress() in doInBackground(). Put your UI-updating logic in onProgressUpdate() of your AsyncTask. onProgressUpdate() will be called on the main application thread (a.k.a., UI thread) after you call publishProgress(). Here is a sample project demonstrating this.

Call runOnUiThread(Runnable action)
more here

Use doInBackground() just for tasks that :
Take some time
Are not UI related
Then you can implement AsyncTask.onPostExecute() to run code to handle those results on main UI thread from AsyncTask
From JavaDoc for AsyncTask.onPostExecute():
"Runs on the UI thread after doInBackground. ... "

As the others have pointed out, you can use runOnUiThread. But, it seems a little odd that you would want to do that in your doInBackground. If you are wanting to indicate progress to the user you would want to handle that in AsyncTask.onProgressUpdate and call publishProgress in your doInBackground.
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
-Dan

Related

Asynchronously load data in android

what is meant by asynchronously loading data in activity or fragment in android?
This is my question. I searched everywhere. I'm not getting a generalized definition for this?. I can't get the term mentioned in android developer also.
Can anyone provide me the basic explanation of this term?
Asynchronous in Android mean that you do stuff while the user can interact with the User Interface (UI) : you are not blocking the UI while you are doing long stuff. So the user can still navigate, change activities or fragment and your data is still loading.
For data : you load it, parse it and do whatever you want in a NON-UI Thread (using AsyncTask eg) and then notify the UI, and display what you need to.
You have many possibilities to implement Asynchronous load in Android, and you have many different way to manage your request. I personnaly recommend using Retrofit if you need to use a Web API.
It means that you load your data in a separate thread than the UI thread. You launch your HTTP request for example in another thread and when it finished you notify the UI thread to refresh display.
This mean to load data in separate thread rather than load the data in main thread.Loading data in main thread may cause app to block
The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.
To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask .
An AsyncTask is started via the execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.
The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

Can a background thread trigger a message handler on UI thread in android

I have a thread which is started in onCreate() and this thread fetches some data.
Is it possible that before the thread is terminated should be able to update the ListView?
Now as the thread is not the UI thread, it cannot directly update the listview array adapter.
Is there a way out?
I was thinking that is it possible to trigger a Handler from thread whose runnable gets executed on main UI thread.
Not sure if I understood your problem completely, but I believe there are two ways to achieve what you want:
1- Start an AsyncTask instead of a thread. AsyncTask's onPostExecute() will run in the UI thread, which means you can do anything UI-related in there. You can start the AsyncTask in onCreate(), and, once it finished, it calls a method on your activity which does:
myAdapter.notifyDataSetChanged();
2- Use runOnUIThread()
Use your Activity's runOnUiThread(Runnable action)
link

Activity's UI freezes on AsyncTask's onPostExecute?

I used AsyncTask to request for a large chunk of data. When received, the data is processed inside the onPostExecute method. It may take a while to process the data.
Based from my understanding, AsyncTask is asynchronous and is independent from the UI.
Why does my Activity freezes onPostExecute?
Is it normal for an Activity to freeze if processing inside the onPostExecute method is too long?
How do I make it such that my Activity won't freeze onPostExecute?
You should do all your datasource operations like(database , network ,parsing the response.etc) in doInBackground method.
If you want update any ui updation in async task the use onProgressUpdate
I think you are performing any parsing operations in onPostExecute. try getting filtered or parsed data (lighter data) in onPostExecute.
Why does my Activity freezes onPostExecute?
According your post, you perform some time consuming operation on
PostExecute method. On PostExecute is running on UI thread, so it's
okay that you UI is freezed.
Is it normal for an Activity to freeze if processing inside the onPostExecute method is too long?
Yes, it's. You should perform long operation in doInBackground method
(non-UI thread)
How do I make it such that my Activity won't freeze onPostExecute?
Try to transfer your long time operation to doInBackground method and
in PostExecute just update UI according response, which you get after
operations in doInBackground method.
see Long Running Task You Need to Bind in doInBackground here you cannot Bind UI control Like Button, ImageView etc. After completion of doInBackground in onPostExecute you can Bind All Require Control, make sure here[onPostExecute] you not runnning Another task.
Make sure you are using doInBackground method in your AsynTask method.

When is the onPreExecute called on an AsyncTask running parallely or concurrently?

I am using Android HoneyComb.I need to execute some tasks parallely and I am using AsyncTask's
public final AsyncTask executeOnExecutor (Executor exec, Params... params) method.In each separate thread I am computing some values and I need to store then in an ArrayList.I must then sort all the values in the arrayList and then display it in the UI.Now my question is if one of the thread gets completed earlier than the other then will it immediately call the onPostExecute method or onPostExecute method will be called after all the background threads have been completed?MY program implementation depends on what occurs here.
Now..... its this way...
AsyncTask synchronized the UI thread, and the Output of the Non-UI work on the Non-UI thread.
onPreExecute() is called on the UI thread, before the Non-UI work starts.
Then doInBackground() executes spinning the Non-UI thread, at this time onProgressUpdate(Progress...) keeps executing simultaneously.... but its highly unpredicatble about its execution.
After the doInBackground(), the onPostExecute() runs on the UI Thread.
See this link for further details:
http://developer.android.com/reference/android/os/AsyncTask.html
Even though using onexecuteExecutor will give you parallel execution, postexecute will be called by each asynctask as soon as it's finished.
But the asynctask will return itself so that you can know which is which if necessary and track their return order.
The doc
As for managing an arraylist from multiple threads, I think you should take a look at Vectors as they are synchronized with a fail-fast behavior. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html

One difference between handler and AsyncTask in Android

Why can an AsyncTask perform only one job? For example,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
But a Handler can continously perform more than one task:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Is an AasyncTask object for a one-time job only? If I don't want to create multiple object for similar task, should I choose Handler?
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
Async task enables you to implement MultiThreading without get Hands dirty into threads. Async Task provides some methods which need to be defined to get your code works. in onPreExecute you can define code, which need to be executed before background processing starts. doInBackground have code which needs to be executed in background, in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread, onPostExecute() method handles results returned by doInBackground method.
So, you dont need to call execute method on AsyncTask multiple TImes, instead you can invoke publishProgress.
Because that is how the class was designed. The idea is: do something with UI (show progress dialog, etc.), do work on background thread and return results, update UI. The Handler is fundamentally different: it lets you post messages, but it does not create a background thread for you. If you don't like how AsyncTask works, build something similar by using threads/executors and handlers.

Categories

Resources