Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

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

I hate inner class.

I've a main activity who launches a 'short-life' AsyncTask.

AsyncTask is in a separate file, is not an inner class of main activity

I need async task updates a textView from main Activity.

I know i can update a TextView from onProgressUpdate, if AsyncTask is a inner class

But how from an external, indipendent, async task ?

UPDATE: This looks like working :

In acitivty i call the task

backgroundTask = new BackgroundTask(this);
backgroundTask.execute();

In the constructor i've

public BackgroundTask(Activity myContext)
{
    debug = (TextView) myContext.findViewById(R.id.debugText);
}

where debug was a private field of AsyncTask.

So onProgressUpdate I can

debug.append(text);

Thanks for all of you suggestions

question from:https://stackoverflow.com/questions/12252654/android-how-to-update-an-ui-from-asynctask-if-asynctask-is-in-a-separate-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...