Skip to content

Instantly share code, notes, and snippets.

@tcw165
Last active April 9, 2017 06:21
Show Gist options
  • Save tcw165/f4468dc0af5d2ac564c5abc466eacf74 to your computer and use it in GitHub Desktop.
Save tcw165/f4468dc0af5d2ac564c5abc466eacf74 to your computer and use it in GitHub Desktop.
/**
* Change the underlying cursor to a new cursor. If there is an existing
* cursor it will be closed.
*/
public void setData(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null && !old.isClosed()) {
old.close();
}
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike
* {@link #setData(Cursor)}, the returned old Cursor is <em>not</em>
* closed.
*/
private Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
final Cursor oldCursor = mCursor;
if (oldCursor != null && mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
oldCursor.close();
}
mCursor = newCursor;
if (mCursor != null) {
if (mDataSetObserver != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
mRowIdColumn = newCursor.getColumnIndexOrThrow(BaseColumns._ID);
mDataValid = true;
} else {
mRowIdColumn = -1;
mDataValid = false;
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
notifyDataSetChanged();
return oldCursor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment