Skip to content

Instantly share code, notes, and snippets.

@cbeyls
Last active April 19, 2018 20:24
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbeyls/e5d0950b4f742cb2bbe1c226137d4e3f to your computer and use it in GitHub Desktop.
Save cbeyls/e5d0950b4f742cb2bbe1c226137d4e3f to your computer and use it in GitHub Desktop.
Simplified CursorAdapter designed for RecyclerView
package be.digitalia.common.adapters;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
/**
* Simplified CursorAdapter designed for RecyclerView.
*
* @author Christophe Beyls
*/
public abstract class RecyclerViewCursorAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private Cursor cursor;
private int rowIDColumn = -1;
public RecyclerViewCursorAdapter() {
setHasStableIds(true);
}
/**
* Swap in a new Cursor, returning the old Cursor.
* The old cursor is not closed.
*
* @param newCursor
* @return The previously set Cursor, if any.
* If the given new Cursor is the same instance as the previously set
* Cursor, null is also returned.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == cursor) {
return null;
}
Cursor oldCursor = cursor;
cursor = newCursor;
rowIDColumn = (newCursor == null) ? -1 : newCursor.getColumnIndexOrThrow("_id");
notifyDataSetChanged();
return oldCursor;
}
public Cursor getCursor() {
return cursor;
}
@Override
public int getItemCount() {
return (cursor == null) ? 0 : cursor.getCount();
}
/**
* @param position
* @return The cursor initialized to the specified position.
*/
public Object getItem(int position) {
if (cursor != null) {
cursor.moveToPosition(position);
}
return cursor;
}
@Override
public long getItemId(int position) {
if ((cursor != null) && cursor.moveToPosition(position)) {
return cursor.getLong(rowIDColumn);
}
return RecyclerView.NO_ID;
}
@Override
public void onBindViewHolder(VH holder, int position) {
if (cursor == null) {
throw new IllegalStateException("this should only be called when the cursor is not null");
}
if (!cursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
onBindViewHolder(holder, cursor);
}
public abstract void onBindViewHolder(VH holder, Cursor cursor);
}
@SanCampos
Copy link

Thank you so much! You are the BEST!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment