Loader restarts on orientation change

Viewed 10471

In the Android documentation for Loaders found at http://developer.android.com/guide/components/loaders.html it says one of the properties of loaders is that:

They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.

The following code does not seem to mirror that behaviour, a new Loader is created an finishes querying the ContentResolver, then I rotate the screen and the Loader is re-created!

public class ReportFragment extends Fragment implements LoaderCallbacks<Cursor> {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLoaderManager().initLoader(1, null, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_report, container, false);
        return v;
    }

    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        Log.d("TEST", "Creating loader");
        return new CursorLoader(getActivity(), ResourcesContract.Reports.CONTENT_URI, null, null, null, null);
    }

    public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
        Log.d("TEST", "Load finished");
    }

    public void onLoaderReset(Loader<Cursor> arg0) {

    }

}

Here is the output from my logcat:

08-17 16:49:54.474: D/TEST(1833): Creating loader
08-17 16:49:55.074: D/TEST(1833): Load finished
*Here I rotate the screen*
08-17 16:50:38.115: D/TEST(1833): Creating loader
08-17 16:50:38.353: D/TEST(1833): Load finished

Any idea what I'm doing wrong here?

EDIT:

I should note that I'm building to Android Google API's version 8, and using the v4 support library.

2nd EDIT:

This is most likely due to a bug in the support library, take a look at this bug submission if you want further information:

http://code.google.com/p/android/issues/detail?id=20791&can=5&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars

6 Answers

Though this is a bit old question I would like to put my views here.

There is no need for storing additional info in onSaveInstanceState

The framework automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.

This means in the onCreate function you need to call loaderManager only if the savedInstanceState is null

Ex:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) {
        getLoaderManager().initLoader(1, null, this);
    }
}
Related