如何停止AsyncTask的同时保留previous选项卡之间切换时正在执行 [英] How to stop AsyncTask being executed when switching between tabs while retaining previous

查看:133
本文介绍了如何停止AsyncTask的同时保留previous选项卡之间切换时正在执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我解释一下我的问题..说我有三个tabs- FragmentTab1 / FragmentTab2 / FragmentTab3。

Let me explain my problem .. say I have three tabs- FragmentTab1 / FragmentTab2 /FragmentTab3.

现在我有列表视图中FragmentTab1。在这里,我加载使用的AsyncTask的 OnCreateView数据()

Now I have listview in FragmentTab1. Here I load data using AsyncTask on OnCreateView().

数据加载完美。现在,当我去的细节,并再次返回到列表视图中FragementTab1。在这里,整个数据再次加载浪费previously加载数据。

Data is loading perfectly. Now when I go for details and again revert back to list view in FragementTab1. Here whole data is loaded again wasting previously loaded data.

现在,在这里我需要一个解决方案,再次停止,并再次执行AsyncTask的,而在回到赛道保持整体观数据就像我们执行pcated TabHost德$ P $的工作。

Now,here I need a solution which stops executing AsyncTask again and again while on back track retaining whole view and data just like we perform work in deprecated TabHost.

任何帮助或建议将是非常美联社preciated。

Any help or suggestion will be highly appreciated.

下面是我的code的东西。

Here is my code stuff.

public class Talk extends Fragment {
   /** Define global variables over here */
   //private ProgressDialog pDialog;
StaticApiList sal;
TalkModelAll tma;
JSONObject myJasonObject = null;
private ListView lv;
private ArrayList<TalkModelAll> m_ArrayList = null;
//ArrayList<String> stringArrayList = new ArrayList<String>();
TalkArrayAdapter taa;
Set<String> uniqueValues = new HashSet<String>();
TextView rowTextView = null;

int postid;
String title;
String thumsrc;
String largeimg;
String excert;
String description;
String cat;
String myUrl;
String jsonString;
int mCurCheckPosition;
String check_state = null;
String ccc;
LinearLayout myLinearLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.talk, container, false);

    new TalkAsyncTask().execute();
    /*if(check_state == null){
    new TalkAsyncTask().execute();
    }else{
        new TalkAsyncTask().execute();
        Toast.makeText(getActivity(), "Have no null value for reloading fragment", Toast.LENGTH_LONG).show();
    }*/


    LinearLayout ll = (LinearLayout) rootView.findViewById(R.id.talk_ll);
    ll.setBackgroundColor(getActivity().getResources().getColor(R.color.talk_red_bottom));

    Log.d("track", "=================> " +uniqueValues.size());
    myLinearLayout = (LinearLayout) rootView.findViewById(R.id.talk_ll_uni);

    return rootView;
}

  private class TalkAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        /*pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();*/
    }

    @Override
    protected String doInBackground(String... params) {
        sal = new StaticApiList();
        myUrl = StaticApiList.talk_api;
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(myUrl);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            System.out.println("httpResponse");

            InputStream inputStream = httpResponse.getEntity().getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String bufferedStrChunk = null;
            while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                stringBuilder.append(bufferedStrChunk);
            }
            jsonString = stringBuilder.toString();
            Log.i("talk_all_json", jsonString);
            return stringBuilder.toString();

        } catch (ClientProtocolException cpe) {
            System.out.println("Exception generates caz of httpResponse :"
                    + cpe);
            cpe.printStackTrace();
        } catch (IOException ioe) {
            System.out
                    .println("Second exception generates caz of httpResponse :"
                            + ioe);
            ioe.printStackTrace();
        }

        return null;
    }

    @SuppressLint("DefaultLocale")
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        check_state = jsonString;
        try{
            m_ArrayList = new ArrayList<TalkModelAll>(); 
            if (jsonString.length() > 0) {
                   JSONArray jArray = new JSONArray(jsonString);

                        for(int i=0; i < jArray.length(); i++) {

                            JSONObject jObject = jArray.getJSONObject(i);

                            title = jObject.getString("title");
                            thumsrc = jObject.getString("thumsrc");
                            largeimg = jObject.getString("largeimg");
                            excert = jObject.getString("excert");
                            description = jObject.getString("description");
                            cat = jObject.getString("cat");
                            postid = jObject.getInt("postid");
                            /////////// stringArrayList.add(jObject.getString("cat"));


                            uniqueValues.add(jObject.getString("cat"));   // Set unique elements in string array list
                             int a = 0;
                                if(a == 0){
                                    uniqueValues.add("All,");
                                     a = 1;
                                }
                            ccc = uniqueValues.toString();
                            Log.d("unique","========================> " + ccc);

                            Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc + " , largeimg -> " + largeimg 
                                    + " , excert -> " + excert + " , description -> " + description + " , cat -> " + cat + " , " + "PostId " + postid );
                            Log.d("talklog", "============================= end of " + i + " ===============================");

                            tma = new TalkModelAll();
                            tma.title = title;
                            tma.thumsrc = thumsrc;
                            tma.largeimg = largeimg;
                            tma.excert = excert;
                            tma.description = description;
                            tma.cat = cat;
                            tma.postid = postid;

                            m_ArrayList.add(tma);

                        } 

                        String[] split_unique = ccc.split(",");

                        Arrays.sort(split_unique);

                        for(int i = 0; i < split_unique.length; i++){
                            Log.d("split_unique", "====>><< " + split_unique.length);
                            Log.d("split_unique", "====>><< " + ccc.split(",")[i]);
                        }

                      //  When we need dynamic number of text view's ..
                     final int N = split_unique.length; // total number of textviews to add

                    final TextView[] myTextViews = new TextView[N]; // create an empty array;

                    for (int i = 0; i < N; i++) {
                       // create a new textview
                       rowTextView = new TextView(getActivity());

                       // set some properties of rowTextView or something talk_ll_uni
                       rowTextView.setText((split_unique[i].replaceAll("[|?*<\":>+\\[\\]/']", "") + "   ").toUpperCase());
                       rowTextView.setTextColor(getActivity().getResources().getColor(R.color.talk_red_bottom));
                       rowTextView.setTextSize(25);
                       rowTextView.setId(i);
                       // add the textview to the linearlayout
                       myLinearLayout.addView(rowTextView);



                       // saving a reference to the textview for later
                       myTextViews[i] = rowTextView;
                   }


                      //if you want your array
                     /////  String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);


            }

            taa = new TalkArrayAdapter(getActivity(), m_ArrayList);
            lv = (ListView) getActivity().findViewById(R.id.talk_list);
            lv.setVisibility(View.VISIBLE); 
            lv.setAdapter(taa);

            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub

                    TalkDetail fragment = new TalkDetail();
                    Bundle bundle = new Bundle();

                    bundle.putString("title", m_ArrayList.get(arg2).title);
                    bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
                    bundle.putString("excert", m_ArrayList.get(arg2).excert);
                    bundle.putString("description", m_ArrayList.get(arg2).description);
                    bundle.putString("cat", m_ArrayList.get(arg2).cat);
                    //bundle.putInt("postid", m_ArrayList.get(arg2).postid);

                    fragment.setArguments(bundle);
                    ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);

                }
            });

        }catch(Exception e){
            e.printStackTrace();
        }

        //pDialog.dismiss();

    }

}

}

我GOOGLE了很多,但没能得到确切的点。我一直在使用其他建议的东西在计算器还检查了不同的方法。

I googled a lot but not able to get exact point. I have also checked that on different methods while using other suggested stuff on StackOverFlow.

在此先感谢您的合作。

推荐答案

有关this..first每当您返回到片段再次,你必须检查是否 Asynchtask 已经执行或不..that手段检查与加载的数据..如果数据空具有负载数据,否则你不需要调用 Asynchtask againn ..

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..

在您的片段维护一个布尔flag..in onPostExecute将其设置为true..whenever你正在移动一个标签到另一个片段您onCreateView方法将被删除并重新添加,所以如果布尔标志是假的执行asynchtask..ohterwise数据已经被加载。

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..

片段停止 AsynchTask 的onDestroy()方法$ C>这样的..

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

这篇关于如何停止AsyncTask的同时保留previous选项卡之间切换时正在执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆