Search code examples
javaandroidandroid-loadermanagerandroid-loader

Swapping a cursor with SimpleAdapterCursor swapCursor()


I've set a content provider in my application and used LoaderManager to load the data but I am having troubles swapping the cursor to a cursor adapter, i tested if cursor is returning data and it is returning! traced the problem and it seems ad.swapCursor(cursor); is the problem.

What do you think i am doing wrong here? is it could be the content provider?

public class Main extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {

public SimpleCursorAdapter ad;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    getLoaderManager().initLoader(0, null, Main.this) != null);
            ad = new SimpleCursorAdapter(this, android.R.id.list, null, null, null, 0); 
}

public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Started!", Toast.LENGTH_SHORT).show();
    CursorLoader cursorLoader = new CursorLoader(getBaseContext(),
            AviatorContentProvider.LISTS_URI, null, null, null, null);
    if(cursorLoader != null){
        Toast.makeText(this, "This thing is heavy!", Toast.LENGTH_SHORT).show();
    }

    return cursorLoader;

}

public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    // TODO Auto-generated method stub
    ad.swapCursor(cursor);

}

public void onLoaderReset(Loader<Cursor> arg0) {
    // TODO Auto-generated method stub

}}

Thanks


Solution

  • You never are initializing your SimpleCursorAdapter "ad". You are likely getting a null pointer exception when trying to call swapCursor on the adapter.

    Initialize your adapter in the onCreate and pass in a null cursor (since no data has been loaded yet).

    String[] from = new String[] { COLUMN_NAME_FROM_YOUR_CURSOR };
    int[] to = new int[] { android.R.id.text1 }; 
    ad = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to,0);
    

    Note where I have "COLUMN_NAME_FROM_YOUR_CURSOR" . You need to put the String value of one of your columns in there (from a constant or a hard-coded value)

    Make sure you check logcat to see the errors you are receiving. It will tell you exactly what the error is and what line of code is causing it.