Andy Drew Obruchkov Andy Drew Obruchkov - 18 days ago 5
Android Question

does swapCursor call newView in the adapter after it is finished

in onLoadFinished() i use myadapter.swapCuesor(cursor) and i wonder if it calls newView in the adapter afterwards? its not written in the api of android's adapter so im asking it here. if not so how the adapter update itself?

Answer

When you are using a CursorLoader, the Cursor is managed for you. The only thing you have to do is implement the following three methods:

    // Called when a new Loader needs to be created
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // Now create and return a CursorLoader that will take care of
    // creating a Cursor for the data being displayed.
    return new CursorLoader(this, ContactsContract.Data.CONTENT_URI,
        PROJECTION, SELECTION, null, null);
   }

   // Called when a previously created loader has finished loading
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in.  (The framework will take care of closing the
    // old cursor once we return.)
    mAdapter.swapCursor(data);
    }

   // Called when a previously created loader is reset, making the data            unavailable
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed.  We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
} 

You don’t have to open and close the Cursor yourself, the loader will do this for you. This is the most important reason why you have to use swapCursor, it doesn’t close the Cursor when you swap it with another Cursor.

    public Cursor swapCursor(Cursor newCursor) {
    if (newCursor == mCursor) {
        return null;
    }
    Cursor oldCursor = mCursor;
    if (oldCursor != null) {
        if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
        if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
    }
    mCursor = newCursor;
    if (newCursor != null) {
        if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
        if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
        mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
        mDataValid = true;
        // notify the observers about the new cursor
        notifyDataSetChanged();
    } else {
        mRowIDColumn = -1;
        mDataValid = false;
        // notify the observers about the lack of a data set
        notifyDataSetInvalidated();
    }
    return oldCursor;
}

ChangeCursor on the other hand, first swaps the current Cursor with the new one and then closes it for you. If you use this method with your CursorLoader, your app may crash sometimes.

    public void changeCursor(Cursor cursor) {
    Cursor old = swapCursor(cursor);
    if (old != null) {
        old.close();
      }
    }