Search code examples
androidandroid-cursoradapterandroid-loadermanager

Using custom CursorAdapter with LoaderManger initialize with null cursor


I have created a custom CursorAdapter to use with my listview and implemented the LoaderManager.LoaderCallbacks functions to load data.

My problem: in my onCreate() method for my activity, I want to create an instance of my CursorAdapter and set it as the adapter for my listview. However, since the LoaderManger has not run my query and returned a cursor yet, I don't have a cursor to pass into the constructor for my adapter. If I pass in null I get a null pointer exception.

With simpleCursorAdapter you are able to pass a null cursor if it hasn't been initialized yet. But I extended CursorAdapter and it doesn't behave the same way.

My question: is there a way to pass a null cursor to my adapter? I get the exception when my constructor calls the super(context, cursor) method of my adapter. I don't do anything else in the constructor.

If I delay creating my adapter (and thus setting it as the adapter to the listview) until the onLoadFinished() call from the LoaderManger, everything works fine, but I am thinking that is not the best way to do this.

I also saw this link:

http://rajeevranganathan.blogspot.com/2012/07/creating-custom-cursor-adapter-and.html

where he re-creates the entire CursorAdapter every time, in essence swapping out the listview's adapter, not simply its cursor - this seems rather inefficient: you shouldn't have to recreate your adapter, just swap out the cursor.

Any help would be greatly appreciated. Am I just going to have to extend SimpleCursorAdapter and simply ignore all the additional arguments I don't need?

Thanks!


Solution

  • If you use the CursorAdaptor constructor with a autoRequery parameter, and pass false, then passing a null cursor is ok:

    class MyCursorAdapter extends CursorAdapter {
    
        MyCursorAdapter(Context context) {
            super(context, null, false);    // cursor=null, autoRequery=false
            .
            .
            .
        }
    }