I am noticing some IllegalStateException
crashes in my analytics report that I can't seem to reproduce. Am I doing something structurally incorrect here? I have included some pseudocode that hopefully shows my fragment's skeleton without being too cluttered. I don't recall seeing this error until I refactored my code to use fragments. The error occurs in AsyncTask's onPostExecute
. Please let me know if I can better clarify my problem / pseudocode better.
public class MyListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
Fragment fragment = this;
SimpleCursorAdapter adapter;
// onActivityCreated initializes the adapter and the loader
public AsyncTaskLoader<Cursor> onCreateloader(int id, Bundle bundle) {
return new CustomCursorLoader(this);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
private class CustomCursorLoader extends CursorLoader {
public CustomCursorLoader(Fragment fragment) {
// get a handle to the OrmLite database helper class
databaseHelper = (DatabaseHelper) OpenHelperManager.getHelper(fragment.getActivity(), DatabaseHelper.class);
}
public Cursor loadInBackground() {
// construct the Cursor that will be used for loading results from the SQLite database
}
}
private class Task extends AsyncTask {
// pre execute
// grab some new database results from the server and repopulate the SQLite database using OrmLite
public void onPostExecute() {
fragment.getLoaderManager().restartLoader(LOADER_ID, null, fragment);
}
}
}
Update
I was able to reproduce the issue by initiating the Task
and then immediately hitting back. When the Task
finishes the activity that contains the fragment is not active so the call to getLoaderManager
fails. The question now is, what is the most elegant way to handle this? I suppose I can just catch the Exception.
Update 2
I believe I can make use of cancel to prevent onPostExecute
from executing. If I do this I will probably need to move initLoader
to another method than onActivityCreated
in order to refresh the loader when the user does come back to the page (since the results updated, just not the loader).
Update 3
I am wondering, like Robby Pond mentions in the comments, if using a Loader here is overkill?