Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

SanCampos commented Dec 27, 2016

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
You can’t perform that action at this time.