How to Update UI from Asynctask

Android: How to update an UI from AsyncTask if AsyncTask is in a separate class?

AsyncTask is always separate class from Activity, but I suspect you mean it is in different file than your activity class file, so you cannot benefit from being activity's inner class. Simply pass Activity context as argument to your Async Task (i.e. to its constructor)

class MyAsyncTask extends AsyncTask<URL, Integer, Long> {

WeakReference<Activity> mWeakActivity;

public MyAsyncTask(Activity activity) {
mWeakActivity = new WeakReference<Activity>(activity);
}

...

and use when you need it (remember to NOT use in during doInBackground()) i.e. so when you would normally call

int id = findViewById(...)

in AsyncTask you call i.e.

Activity activity = mWeakActivity.get();
if (activity != null) {
int id = activity.findViewById(...);
}

Note that our Activity can be gone while doInBackground() is in progress (so the reference returned can become null), but by using WeakReference we do not prevent GC from collecting it (and leaking memory) and as Activity is gone, it's usually pointless to even try to update it state (still, depending on your logic you may want to do something like changing internal state or update DB, but touching UI must be skipped).

AsyncTask - after execution, how to update view?

If you want to update the view from async after complete process in then
you can use

protected void onPostExecute(String result)
{
textView.setText(result);
}

But if you want to update data while running background process then use.
For ex...

protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));<------
}
return totalSize;
}

protected void onProgressUpdate(Integer... progress) { <-------
setProgressPercent(progress[0]);
}

for more detail see this link
Hope this will help you...!

Cannot update UI from AsyncTask

you connot make a new object from an activity and work with it. try to get a reference to the activity

add this code to your AsyncTask class

MainActivity activity;

public void setContext(MainActivity activity){
this.activity = activity;
}

also edit this

@Override
protected void onPostExecute(String result) {
activity.updateTextView(result);
}

call this method when you create your AsyncTask object in your activity

//at is the object you created from your AsyncTask Class
at.setContext(this);

How to update UI on external asynctask on android

Do not call onProgressUpdate(). Instead just call publishProgress("The String").

By calling publishProgress without a parameter you will have no values in onProgressUpdate. That's why you get an IndexOutOfBondException.



Related Topics



Leave a reply



Submit