简体   繁体   中英

Asynctask in Fragment or Parent Activity?

I have a scenario and I an not sure on what path to go.

Scenario

The app has a Home activity which displays various fragments. The data in the fragments can come either from the web or a local database and is retrieved using an asynctask.

From what I saw, I have 2 alternatives:

  1. Put the Asynctask in parent activity and then use fragment.newInstance(parameters) to pass the result to the fragment. However, if in my asynctask I need to update the progress or some info on the fragment, each time I will have to call newInstance with the new set of parameters.

  2. Add the fragment and put the asynctask in it, in this way when progress is needed, I can update the fragment's views, as I have access to them + when the asynctask is done, I can populate the list with the info.

What would be the correct approach ?

LE: actually for point 1 in order to update the fragment I can call fragment's public methods after I find it with findFragmentById in the parent activity

A better way if you have multiple tasks would be to use an IntentService : http://mobile.tutsplus.com/tutorials/android/android-fundamentals-intentservice-basics/

You would have a better control to what you're requesting and what you want to cancel.

I would go with the second approach.
My primary reason though would be to avoid the issues that can happen on screen orientation change while the AsyncTask is working.

I would go with method 2, but take it a step further.

Have a separate fragment to run your async task. This way, you can handle any configuration changes (not just rotating screen) without any issues.

In another fragment, you can display the data. You can pass the data from your async task fragment via callbacks to the activity, and have the activity call a method in the display fragment to update the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM