Handling AsyncTask
suggest changeProblem:
- If after the
AsyncTaskstarts there is a screen rotation the owning activity is destroyed and recreated. - When the
AsyncTaskfinishes, it wants to update a UI that may no longer be valid.
Solution:
Using Loaders, one can easily overcome the activity destruction/recreation.
Example:
MainActivity:
public class MainActivity extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Bitmap> {
//Unique id for the loader
private static final int MY_LOADER = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call initLoader on every onCreate so the new activity is attached after rotation.
getSupportLoaderManager().initLoader(MY_LOADER, null, this);
}
@Override
public Loader<Bitmap> onCreateLoader(int id, Bundle args) {
//Create a new instance of your Loader<Bitmap>
MyLoader loader = new MyLoader(MainActivity.this);
return loader;
}
@Override
public void onLoadFinished(Loader<Bitmap> loader, Bitmap data) {
// do something in the parent activity/service
// i.e. display the downloaded image
Log.d("MyAsyncTask", "Received result: ");
}
@Override
public void onLoaderReset(Loader<Bitmap> loader) {
}
}
AsyncTaskLoader:
public class MyLoader extends AsyncTaskLoader<Bitmap> {
private WeakReference<Activity> motherActivity;
private Bitmap cached;
public MyLoader(Activity activity) {
super(activity);
//We don't use this, but if you want you can use it, but remember, WeakReference
motherActivity = new WeakReference<>(activity);
}
@Override
protected void onStartLoading() {
if (cached != null) {
deliverResult(cached);
} else {
forceLoad();
}
}
@Override
public Bitmap loadInBackground() {
// Download the image and return that Bitmap.
Bitmap result = null;
cached = result;
return result;
}
}
Note:
It is important to use either the v4 compatibility library or not, but do not use part of one and part of the other, as it will lead to compilation errors. To check you can look at the imports for android.support.v4.content and android.content (you shouldn’t have both).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents