Updating an Activity from an AsyncTask?

AsyncTask is designed to work best when nested in an Activity class.

AsyncTask is designed to work best when nested in an Activity class. What makes AsyncTask 'special' is that it isn't just a worker thread - instead it combines a worker thread which processes the code in doInBackground(...) with methods which run on the Activity's UI thread - onProgressUpdate(...) and onPostExecute(...) being the most commonly used. By periodically calling updateProgress(...) from doInBackground(...), the onProgressUpdate(...) method is called allowing it to manipulate the Activity's UI elements (progress bar, text to show name of file being downloaded, etc etc).

In short, rather than firing your 'update' Activity from an AsyncTask, your update Activity itself should have a nested AsyncTask which it uses to process the update and publish progress to the UI.

I guess to me it seems better to have one class manage all data, and another manage the UI. But with android that is not the case? Does this mean I need to create new instances of my database helpers in the update class then?

I think I see how this can be done, It is just different to me. – mouser58907 Jun 2 at 16:21 @mouser: The way I've done it for my current app is I have a 'db helper' class which extends SQLiteOpenHelper. I also extend the Application class which maintains a static reference to a single instance of the db helper.

This means that all Activities etc can access the helper by using MyApp. DbHelper – MisterSquonk Jun 2 at 16:27.

You have two options: 1) Pass an instance of activity to your AsyncTask constructor in order to invoke some method on it: new MyTask(this).execute(); So, you can do: public MyTask (Activity activity) { this. Activity = activity; } public void onPostExecute(...) { activity.someMethod(); } 2) Pass a Handler instance and send message from onPostExecute() to the activity.

– mouser58907 Jun 2 at 13:52 See the updated answer. Also, handler is better for many reasons. One of them is that you hide the implementation details of the activity from another class thus lowering the coupling.

– Vladimir Ivanov Jun 2 at 14:34 I'm attempting the first method and it is not working so well. This is what I have in onPreExecute, the second line makes it crash: Intent myIntent = new Intent(mContext,UpdateActivity. Class); updateActivity.

StartActivity(myIntent); – mouser58907 Jun 2 at 15:52.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions