MyListFragment
は、AsyncTask を使用して REST サービスからデータをフェッチします。ブロックはonPostExecute()
、結果ではなく、成功/失敗ステータスをフラグメントに返します。私のフラグメントでは、このステータスを使用して、ListView
(成功の場合) 表示するか、(失敗の場合) トーストをポップアップします。
が実行されるとすぐに、アクティビティ サークルが画面の中央に表示され、データが利用可能AsyncTask
になると に置き換えられます。ListView
データが利用できない場合、トースト メッセージはポップアップしますが、アクティビティ サークルは削除されません。アクティビティ スピナーをいつ開始するかは、コードのどこにも宣言していません。
失敗した場合、活動サークルを停止するにはどうすればよいですか?
のコード ブロックは次のAsyncTask
とおりです。
class invokeServiceTask extends AsyncTask<String, Void, ServiceResult> {
@Override
// method to be run in BG thread
// pass the mashup parameters to the BG thread
protected ServiceResult doInBackground(String... id) {
return invokeMashupService(id);
}
@Override
// called on UI thread when the worker is done
protected void onPostExecute(ServiceResult result) {
_delegate.mashupReturned(result);
}
}
結果が SERVICE_FAILURE として返された場合、完了後に UI で実行される以下のコード ブロックに見られるようにトーストを表示していますAsyncTask
。
public void mashupReturned(ServiceResult result) {
// check for getActivity to counter the case when user presses the back
// button quickly and the app context is no longer valid.
if (getActivity() != null) {
if (result == ServiceResult.SERVICE_SUCCESS) {
// Fetch the array of GroupListItems and create a
// GroupListAdapter using it
GroupListItem[] list_data = _dataModel.getData();
GroupListAdapter adapter = new GroupListAdapter(getActivity(),
R.layout.list_row, list_data);
setListAdapter(adapter);
} else {
// TODO: stop the activity spinner
Toast.makeText(getActivity(),
"Problem invoking service: " + result,
Toast.LENGTH_SHORT).show();
}
} else {
Log.i("test", "Activity is null");
}
}