Android 如何在保留上一个选项卡的同时在选项卡之间切换时停止正在执行的异步任务

Android 如何在保留上一个选项卡的同时在选项卡之间切换时停止正在执行的异步任务,android,Android,让我解释一下我的问题。。假设我有三个选项卡-FragmentTab1/FragmentTab2/FragmentTab3 现在我在FragmentTab1中有了listview。在这里,我在OnCreateView()上使用AsyncTask加载数据 数据正在完美加载。现在,当我查看详细信息并再次返回FragementTab1中的列表视图时。在此,将再次加载整个数据,从而浪费先前加载的数据 现在,我需要一个解决方案,它可以一次又一次地停止执行AsyncTask,同时保留整个视图和数据,就像我们在

让我解释一下我的问题。。假设我有三个选项卡-FragmentTab1/FragmentTab2/FragmentTab3

现在我在FragmentTab1中有了listview。在这里,我在
OnCreateView()上使用AsyncTask加载数据

数据正在完美加载。现在,当我查看详细信息并再次返回FragementTab1中的列表视图时。在此,将再次加载整个数据,从而浪费先前加载的数据

现在,我需要一个解决方案,它可以一次又一次地停止执行AsyncTask,同时保留整个视图和数据,就像我们在不推荐使用的TabHost中执行工作一样

如有任何帮助或建议,将不胜感激

这是我的代码

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

    }

}
公共类对话扩展片段{
/**在这里定义全局变量*/
//私人对话;
蜂王属植物;
所有tma;
JSONObject myJasonObject=null;
私有ListView lv;
私有ArrayList m_ArrayList=null;
//ArrayList stringArrayList=新的ArrayList();
TalkArrayAdapterTAA;
Set uniqueValues=new HashSet();
TextView行TextView=null;
国际邮政;
字符串标题;
字符串thumsrc;
弦大;
字符串过量;
字符串描述;
弦猫;
字符串myUrl;
字符串jsonString;
int mCurCheckPosition;
字符串检查_state=null;
字符串ccc;
线性布局我的线性布局;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.talk,container,false);
新建TalkAsyncTask().execute();
/*如果(检查状态==null){
新建TalkAsyncTask().execute();
}否则{
新建TalkAsyncTask().execute();
Toast.makeText(getActivity(),“没有空值用于重新加载片段”,Toast.LENGTH_LONG.show();
}*/
LinearLayout ll=(LinearLayout)rootView.findViewById(R.id.talk\ll);
ll.setBackgroundColor(getActivity().getResources().getColor(R.color.talk\u red\u bottom));
Log.d(“track”、“===================>”+uniqueValues.size());
myLinearLayout=(LinearLayout)rootView.findviewbyd(R.id.talk\u ll\u uni);
返回rootView;
}
私有类TalkAsyncTask扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
/*pDialog=newprogressdialog(getActivity());
setMessage(“请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show()*/
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
sal=新的静态APIList();
myUrl=StaticApiList.talk\u api;
HttpClient HttpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(myUrl);
试一试{
HttpResponse HttpResponse=httpClient.execute(httpGet);
System.out.println(“httpResponse”);
InputStream InputStream=httpResponse.getEntity().getContent();
InputStreamReader InputStreamReader=新的InputStreamReader(
输入流);
BufferedReader BufferedReader=新的BufferedReader(
输入流阅读器);
StringBuilder StringBuilder=新的StringBuilder();
字符串bufferedStrChunk=null;
while((bufferedStrChunk=bufferedReader.readLine())!=null){
追加(bufferedStrChunk);
}
jsonString=stringBuilder.toString();
Log.i(“talk\u all\u json”,jsonString);
返回stringBuilder.toString();
}捕获(客户端协议异常cpe){
System.out.println(“异常生成httpResponse的caz:”
+cpe);
printStackTrace();
}捕获(ioe异常ioe){
系统输出
.println(“第二个异常生成httpResponse的caz:”
+ioe);
ioe.printStackTrace();
}
返回null;
}
@SuppressLint(“DefaultLocale”)
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
检查_state=jsonString;
试一试{
m_ArrayList=新的ArrayList();
if(jsonString.length()>0){
JSONArray jArray=新的JSONArray(jsonString);
for(int i=0;i”+ccc);
Log.d(“talklog”,“Title->”,“Title+”,thumsrc->“+thumsrc+”,largeimg->“+largeimg
+“、超出->”+超出+”、说明->“+说明+”、类别->“+cat+”、“+”PostId”+PostId);
日志d(“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“talklog”,“i+”的结尾;
@Override
public void onDestroy() {
    super.onDestroy();
    if (applicationLoadTask != null) {
        if (!applicationLoadTask.isCancelled()) {
            applicationLoadTask.cancel(true);
        }
    }
}
// cancelling asynck-task if it is running

 if(yourTask.getStatus() == AsyncTask.Running){
   yourTask.cancel();
}