我正在使用this文章中描述的方法,在Fragment的AsyncTask中下載並解析html頁面。一切工作正常仿真器,但後來我在我的Galaxy S2上嘗試。當我旋轉我的設備,listview不刷新,如果我旋轉設備回來,它刷新。片段中的AsyncTask
下面是我如何使用我的片段中的onCreate代碼(LinksDownloader - 類解析HTML)
FragmentManager fm = getSupportFragmentManager();
mTaskFragment = (DownloadLinksTaskFragment) fm.findFragmentByTag("task");
if (mTaskFragment == null){
mTaskFragment = new DownloadLinksTaskFragment();
mTaskFragment.linksDownloader = new LinksDownloader();
fm.beginTransaction().add(mTaskFragment, "task").commit();
}
...
goButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mTaskFragment.execute();
}
});
...
linksAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, mTaskFragment.linksDownloader.linksArray);
linksListView.setAdapter(linksAdapter);
和片斷類
public class DownloadLinksTaskFragment extends Fragment {
static interface TaskCallbacks {
void onPreExecute();
void onPostExecute(Byte mssg);
}
private TaskCallbacks mCallbacks;
private DownloadLinksTask mTask;
public LinksDownloader linksDownloader;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (TaskCallbacks) activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
public void execute() {
mTask = new DownloadLinksTask();
mTask.execute();
}
private class DownloadLinksTask extends AsyncTask<Void, Void, Byte> {
@Override
protected void onPreExecute() {
if (mCallbacks != null) {
mCallbacks.onPreExecute();
}
}
@Override
protected void onPostExecute(Byte b) {
if (mCallbacks != null) {
mCallbacks.onPostExecute(b);
}
}
@Override
protected Byte doInBackground(Void... v) {
byte exceptionType = 0;
try {
linksDownloader.download();
} catch (HttpStatusException e) {
exceptionType = 1;
} catch (WrongContentException e) {
exceptionType = 2;
} catch (ConnectTimeoutException e) {
exceptionType = 3;
} catch (SocketTimeoutException e) {
exceptionType = 3;
} catch (UnknownHostException e) {
exceptionType = 3;
} catch (IOException e) {
exceptionType = 4;
} catch (Exception e) {
exceptionType = 5;
}
return exceptionType;
}
}
}