Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 377
Alin Avatar asked Aug 09 '13 09:08

Alin


1 Answers

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.

like image 110
NitroG42 Avatar answered Oct 21 '22 12:10

NitroG42