Let me explain my problem .. say I have three tabs- FragmentTab1 / FragmentTab2 /FragmentTab3.
Now I have listview in FragmentTab1. Here I load data using AsyncTask
For this..first whenever you return back to the fragment
again you have to check whether the Asynchtask
already executed or not ..that means check with the loaded data ..if data null you have load data otherwise you no need to call Asynchtask
againn..
In your fragment maintain one boolean flag..in onPostExecute set it to true..whenever you are moving one tab to another fragment will be removed and again added so in your onCreateView method if boolean flag is false execute asynchtask..ohterwise data is already loaded..
or maintain a one singleton
class and set your loaded data again moving back to activity gat data from singleton class and if data is null load load it and set to the singleton class..
In your onDestroy()
method of fragment
stop the AsynchTask
like this..
@Override
public void onDestroy() {
super.onDestroy();
if (applicationLoadTask != null) {
if (!applicationLoadTask.isCancelled()) {
applicationLoadTask.cancel(true);
}
}
}
You need to create a class that will store the data you just fetched from execution of AsyncTask. In onPostExecute() save the fetched data in this class's object, and in some other method(say A()) show the data from class's object to your views.
When you will navigate between tabs, check if that Object has data, If it has then call A() otherwise re-execute the Async-Task to fetch the data.
This seems more of design issue.
// cancelling asynck-task if it is running
if(yourTask.getStatus() == AsyncTask.Running){
yourTask.cancel();
}
Similarly you can check for other states of async-task as per your requirement. Refer : this