Skip to content

Instantly share code, notes, and snippets.

@mrolcsi
Last active October 8, 2015 07:57
Show Gist options
  • Save mrolcsi/92a975540a74fdc7c092 to your computer and use it in GitHub Desktop.
Save mrolcsi/92a975540a74fdc7c092 to your computer and use it in GitHub Desktop.
Cursor support for not-cursor adapters
public class CursorAdapter extends AnyAdapter {
private int mCount;
private Cursor mCursor;
private boolean mDataValid;
private DataSetObserver mDataSetObserver;
public CursorAdapter(Cursor cursor){
super();
mCursor = cursor;
mDataValid = cursor != null;
mDataSetObserver = new NotifyingDataSetObserver();
if (mCursor != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
findIndices();
}
}
@Override
public int getCount() {
if (mCursor != null && !mCursor.isClosed()) {
mCount = mCursor.getCount();
}
return mCount;
}
/**
* Change the underlying cursor to a new cursor. If there is an existing cursor it will be
* closed.
*/
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close();
}
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike
* {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
* closed.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
final Cursor oldCursor = mCursor;
if (oldCursor != null && mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (mCursor != null) {
if (mDataSetObserver != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
mDataValid = true;
findIndices();
notifyDataSetChanged();
} else {
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
return oldCursor;
}
protected void findIndices(){
//TODO: store column indices in fields.
}
private class NotifyingDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
super.onChanged();
mDataValid = true;
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment