Advertisement
Guest User

Untitled

a guest
Dec 13th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. import android.database.Cursor;
  2. import android.support.v7.widget.RecyclerView;
  3.  
  4.  
  5. public abstract class BaseCursorAdapter <V extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<V> {
  6. private Cursor mCursor;
  7. private boolean mDataValid;
  8. private int mRowIDColumn;
  9.  
  10. public abstract void onBindViewHolder(V holder, Cursor cursor);
  11.  
  12. public BaseCursorAdapter(Cursor c) {
  13. setHasStableIds(true);
  14. swapCursor(c);
  15. }
  16.  
  17. @Override
  18. public void onBindViewHolder(V holder, int position) {
  19.  
  20. if (!mDataValid) {
  21. throw new IllegalStateException("Cannot bind view holder when cursor is in invalid state.");
  22. }
  23. if (!mCursor.moveToPosition(position)) {
  24. throw new IllegalStateException("Could not move cursor to position " + position + " when trying to bind view holder");
  25. }
  26.  
  27. onBindViewHolder(holder, mCursor);
  28. }
  29.  
  30. @Override
  31. public int getItemCount() {
  32. if (mDataValid) {
  33. return mCursor.getCount();
  34. } else {
  35. return 0;
  36. }
  37. }
  38.  
  39. @Override
  40. public long getItemId(int position) {
  41. if (!mDataValid) {
  42. throw new IllegalStateException("Cannot lookup item id when cursor is in invalid state.");
  43. }
  44. if (!mCursor.moveToPosition(position)) {
  45. throw new IllegalStateException("Could not move cursor to position " + position + " when trying to get an item id");
  46. }
  47.  
  48. return mCursor.getLong(mRowIDColumn);
  49. }
  50.  
  51. public Cursor getItem(int position) {
  52. if (!mDataValid) {
  53. throw new IllegalStateException("Cannot lookup item id when cursor is in invalid state.");
  54. }
  55. if (!mCursor.moveToPosition(position)) {
  56. throw new IllegalStateException("Could not move cursor to position " + position + " when trying to get an item id");
  57. }
  58. return mCursor;
  59. }
  60.  
  61. public void swapCursor(Cursor newCursor) {
  62. if (newCursor == mCursor) {
  63. return;
  64. }
  65.  
  66. if (newCursor != null) {
  67. mCursor = newCursor;
  68. mDataValid = true;
  69. // notify the observers about the new cursor
  70. notifyDataSetChanged();
  71. } else {
  72. notifyItemRangeRemoved(0, getItemCount());
  73. mCursor = null;
  74. mRowIDColumn = -1;
  75. mDataValid = false;
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement