Phoenixblade9's answer is correct, but to make it complete, I would add one thing.
There's a great replacement for AsyncTask - AsyncTaskLoader or Loaders in general. It manages the life cycle according to the context from which it was called (Activity, Fragment), and implements a bunch of listeners to help you separate the logic of the second thread from the ui thread. And this is usually immune to the current context.
And do not worry about the name - it is also useful for saving data.
As promised, I will send my code for AsyncTaskLoader along with several returned objects. The bootloader looks something like this:
public class ItemsLoader extends AsyncTaskLoader<HashMap<String, Object>>{ HashMap<String, Object> returned; ArrayList<SomeItem> items; Context cxt; public EventsLoader(Context context) { super(context); //here you can initialize your vars and get your context if you need it inside } @Override public HashMap<String, Object> loadInBackground() { returned = getYourData(); return returned; } @Override public void deliverResult(HashMap<String, Object> returned) { if (isReset()) { return; } this.returned = returned; super.deliverResult(returned); } @Override protected void onStartLoading() { if (returned != null) { deliverResult(returned); } if (takeContentChanged() || returned == null) { forceLoad(); } } @Override protected void onStopLoading() { cancelLoad(); } @Override protected void onReset() { super.onReset(); onStopLoading(); returned = null; }
In the getYourData()
function, I get the server code code or another error code and ArrayList<SomeItem>
. I can use them in my fragment as follows:
public class ItemListFragment extends ListFragment implements LoaderCallbacks<HashMap<String, Object>>{ private LoaderManager lm; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); lm = getLoaderManager(); Bundle args = new Bundle(); args.putInt("someId", someId); lm.initLoader(0, args, this); } @Override public Loader<HashMap<String, Object>> onCreateLoader(int arg0, Bundle args) { ItemsLoader loader = new ItemsLoader(getActivity(), args.getInt("someId")); return loader; } @Override public void onLoadFinished(Loader<HashMap<String, Object>> loader, HashMap<String, Object> data) { if(data!=null){ if(data.containsKey("items")){ ArrayList<SomeItem> items = (ArrayList<EventItem>)data.get("items"); } else {
source share