Search code examples
javaandroidandroid-sqliteandroid-cursoradapterandroid-cursorloader

How to maintain state of filtered CursorAdapter through orientation changes?


I have an application that helps users organize prescriptions. I have one listview that shows medications and I use an EditText to allow the user to filter the list. The problem I'm having is that the CursorLoader is replaced each time the orientation changes.

From what I understand, the LoaderManager.initLoader() function should be called in onActivityCreated(). In my particular case, I don't have a fragment so I put the initLoader() call inside onPostCreate():

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    getSupportLoaderManager().initLoader(MEDICATION_LOADER, null, this);
}

And here is the filter I'm using:

// Set text filter
mMedication.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mMedicationAdapter.getFilter().filter(s);
    }
});

I removed the empty beforeTextChanged and afterTextChanged methods to shorten this.

So, what appears to be happening (from using the debugger) is that each time I change the device orientation, initLoader() is called again and the entire list of medications are displayed, not just the filtered ones. Is there a way to implement onSaveInstanceState() to store the current filtered state of the adapter?

Or am I using the text filter wrong? Should I pass the charSequence as a Bundle argument to the loader, or create another loader that handles the text as an argument?


Solution

  • A solution is you can keep the current activity when orientation changes, Just set the Activity to handle config changes in AndroidManifest.xml: Android config changes

    e.g.

     <activity
            android:name="com.test.MyActivity"
            android:configChanges="screenSize|orientation"/>