Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is CursorLoader onLoaderReset() called after device rotation?

I have a main Activity A that uses a CursorLoader to query a DB. This I create in the activity onCreate() method:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    getSupportLoaderManager().initLoader(LOADER_MEASUREMENTS, null, A.this);
}

Activity A also implements the 3 callbacks for the CursorLoader:

public Loader<Cursor> onCreateLoader(int loaderId, Bundle args)
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor)
public void onLoaderReset(Loader<Cursor> loader)

When I rotate the device, I see the correct lifecycle methods run:

A.onPause()
A.onStop()
A.onDestroy()          
A.onCreate()      <-- re-connect to existing loader, onCreateLoader() not called
A.onLoadFinished()
A.onStart()
A.onResume()

Then I open a sub-Activity B and rotate my device. When I finish B and return to Activity A I see the following run:

B.onPause()
       A.onLoaderReset()      <- why does this run?
       A.onDestroy()          
       A.onCreate()
       A.onCreateLoader()     <- now runs as loader is null
       A.onStart()
       ...

Why is my loader reset because I had Activity B open and did a device rotate? Just to add that Activity B has nothing to do with the DB or the CursorLoader.

like image 854
MickeyR Avatar asked May 08 '16 11:05

MickeyR


1 Answers

I checked the LoaderManager source code you'll find this method:

/**
     * Stops and removes the loader with the given ID.  If this loader
     * had previously reported data to the client through
     * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
     * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
     */
    public abstract void destroyLoader(int id);

It appears that you loader gets destroyed when rotating the screen (due to configuration change). The LoaderManager internally calls the destroyLoader method which in turn calls the onLoaderReset callback method.

like image 98
Mina Wissa Avatar answered Oct 04 '22 17:10

Mina Wissa