Last active
April 19, 2018 20:24
-
-
Save cbeyls/e5d0950b4f742cb2bbe1c226137d4e3f to your computer and use it in GitHub Desktop.
Simplified CursorAdapter designed for RecyclerView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much! You are the BEST!