Как остановить выполнение AsyncTask при переключении между вкладками при сохранении предыдущего
Позвольте мне объяснить мою проблему .. скажем, у меня есть три вкладки - FragmentTab1 / FragmentTab2 / FragmentTab3.
Теперь у меня есть просмотр списка в FragmentTab1. Здесь я загружаю данные, используя AsyncTask.OnCreateView()
Данные загружаются отлично. Теперь, когда я перейду к деталям и снова вернусь к списку в 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 m_ArrayList = null;
//ArrayList stringArrayList = new ArrayList();
TalkArrayAdapter taa;
Set uniqueValues = new HashSet();
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 {
@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();
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("[|?*