How to stop AsyncTask being executed when switching between tabs while retaining previous

后端 未结 2 1656
天涯浪人
天涯浪人 2021-01-15 20:14

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 20:40

    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);
            }
        }
    }
    

提交回复
热议问题