Skip to content

Instantly share code, notes, and snippets.

@Shywim
Last active February 27, 2024 13:42
Show Gist options
  • Save Shywim/127f207e7248fe48400b to your computer and use it in GitHub Desktop.
Save Shywim/127f207e7248fe48400b to your computer and use it in GitHub Desktop.
A custom Adapter for the new RecyclerView, behaving like the CursorAdapter class from previous ListView and alike. Now with Filters and updated doc.
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Matthieu Harlé
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.widget.Filter;
import android.widget.FilterQueryProvider;
import android.widget.Filterable;
/**
* Provide a {@link android.support.v7.widget.RecyclerView.Adapter} implementation with cursor
* support.
*
* Child classes only need to implement {@link #onCreateViewHolder(android.view.ViewGroup, int)} and
* {@link #onBindViewHolderCursor(android.support.v7.widget.RecyclerView.ViewHolder, android.database.Cursor)}.
*
* This class does not implement deprecated fields and methods from CursorAdapter! Incidentally,
* only {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER} is available, so the
* flag is implied, and only the Adapter behavior using this flag has been ported.
*
* @param <VH> {@inheritDoc}
*
* @see android.support.v7.widget.RecyclerView.Adapter
* @see android.widget.CursorAdapter
* @see android.widget.Filterable
* @see fr.shywim.tools.adapter.CursorFilter.CursorFilterClient
*/
public abstract class CursorRecyclerAdapter<VH
extends android.support.v7.widget.RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>
implements Filterable, CursorFilter.CursorFilterClient {
private boolean mDataValid;
private int mRowIDColumn;
private Cursor mCursor;
private ChangeObserver mChangeObserver;
private DataSetObserver mDataSetObserver;
private CursorFilter mCursorFilter;
private FilterQueryProvider mFilterQueryProvider;
public CursorRecyclerAdapter( Cursor cursor) {
init(cursor);
}
void init(Cursor c) {
boolean cursorPresent = c != null;
mCursor = c;
mDataValid = cursorPresent;
mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1;
mChangeObserver = new ChangeObserver();
mDataSetObserver = new MyDataSetObserver();
if (cursorPresent) {
if (mChangeObserver != null) c.registerContentObserver(mChangeObserver);
if (mDataSetObserver != null) c.registerDataSetObserver(mDataSetObserver);
}
}
/**
* This method will move the Cursor to the correct position and call
* {@link #onBindViewHolderCursor(android.support.v7.widget.RecyclerView.ViewHolder,
* android.database.Cursor)}.
*
* @param holder {@inheritDoc}
* @param i {@inheritDoc}
*/
@Override
public void onBindViewHolder(VH holder, int i){
if (!mDataValid) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(i)) {
throw new IllegalStateException("couldn't move cursor to position " + i);
}
onBindViewHolderCursor(holder, mCursor);
}
/**
* See {@link android.widget.CursorAdapter#bindView(android.view.View, android.content.Context,
* android.database.Cursor)},
* {@link #onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder, int)}
*
* @param holder View holder.
* @param cursor The cursor from which to get the data. The cursor is already
* moved to the correct position.
*/
public abstract void onBindViewHolderCursor(VH holder, Cursor cursor);
@Override
public int getItemCount() {
if (mDataValid && mCursor != null) {
return mCursor.getCount();
} else {
return 0;
}
}
/**
* @see android.widget.ListAdapter#getItemId(int)
*/
@Override
public long getItemId(int position) {
if (mDataValid && mCursor != null) {
if (mCursor.moveToPosition(position)) {
return mCursor.getLong(mRowIDColumn);
} else {
return 0;
}
} else {
return 0;
}
}
public Cursor getCursor(){
return mCursor;
}
/**
* Change the underlying cursor to a new cursor. If there is an existing cursor it will be
* closed.
*
* @param cursor The new cursor to be used
*/
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.
*
* @param newCursor The new cursor to be used.
* @return Returns the previously set Cursor, or null if there wasa not one.
* If the given new Cursor is the same instance is the previously set
* Cursor, null is also returned.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
Cursor oldCursor = mCursor;
if (oldCursor != null) {
if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (newCursor != null) {
if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
// notify the observers about the new cursor
notifyDataSetChanged();
} else {
mRowIDColumn = -1;
mDataValid = false;
// notify the observers about the lack of a data set
// notifyDataSetInvalidated();
notifyItemRangeRemoved(0, getItemCount());
}
return oldCursor;
}
/**
* <p>Converts the cursor into a CharSequence. Subclasses should override this
* method to convert their results. The default implementation returns an
* empty String for null values or the default String representation of
* the value.</p>
*
* @param cursor the cursor to convert to a CharSequence
* @return a CharSequence representing the value
*/
public CharSequence convertToString(Cursor cursor) {
return cursor == null ? "" : cursor.toString();
}
/**
* Runs a query with the specified constraint. This query is requested
* by the filter attached to this adapter.
*
* The query is provided by a
* {@link android.widget.FilterQueryProvider}.
* If no provider is specified, the current cursor is not filtered and returned.
*
* After this method returns the resulting cursor is passed to {@link #changeCursor(Cursor)}
* and the previous cursor is closed.
*
* This method is always executed on a background thread, not on the
* application's main thread (or UI thread.)
*
* Contract: when constraint is null or empty, the original results,
* prior to any filtering, must be returned.
*
* @param constraint the constraint with which the query must be filtered
*
* @return a Cursor representing the results of the new query
*
* @see #getFilter()
* @see #getFilterQueryProvider()
* @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
*/
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (mFilterQueryProvider != null) {
return mFilterQueryProvider.runQuery(constraint);
}
return mCursor;
}
public Filter getFilter() {
if (mCursorFilter == null) {
mCursorFilter = new CursorFilter(this);
}
return mCursorFilter;
}
/**
* Returns the query filter provider used for filtering. When the
* provider is null, no filtering occurs.
*
* @return the current filter query provider or null if it does not exist
*
* @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
* @see #runQueryOnBackgroundThread(CharSequence)
*/
public FilterQueryProvider getFilterQueryProvider() {
return mFilterQueryProvider;
}
/**
* Sets the query filter provider used to filter the current Cursor.
* The provider's
* {@link android.widget.FilterQueryProvider#runQuery(CharSequence)}
* method is invoked when filtering is requested by a client of
* this adapter.
*
* @param filterQueryProvider the filter query provider or null to remove it
*
* @see #getFilterQueryProvider()
* @see #runQueryOnBackgroundThread(CharSequence)
*/
public void setFilterQueryProvider(FilterQueryProvider filterQueryProvider) {
mFilterQueryProvider = filterQueryProvider;
}
/**
* Called when the {@link ContentObserver} on the cursor receives a change notification.
* Can be implemented by sub-class.
*
* @see ContentObserver#onChange(boolean)
*/
protected void onContentChanged() {
}
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
onContentChanged();
}
}
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
mDataValid = true;
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
mDataValid = false;
// notifyDataSetInvalidated();
notifyItemRangeRemoved(0, getItemCount());
}
}
/**
* <p>The CursorFilter delegates most of the work to the CursorAdapter.
* Subclasses should override these delegate methods to run the queries
* and convert the results into String that can be used by auto-completion
* widgets.</p>
*/
}
class CursorFilter extends Filter {
CursorFilterClient mClient;
interface CursorFilterClient {
CharSequence convertToString(Cursor cursor);
Cursor runQueryOnBackgroundThread(CharSequence constraint);
Cursor getCursor();
void changeCursor(Cursor cursor);
}
CursorFilter(CursorFilterClient client) {
mClient = client;
}
@Override
public CharSequence convertResultToString(Object resultValue) {
return mClient.convertToString((Cursor) resultValue);
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
Cursor cursor = mClient.runQueryOnBackgroundThread(constraint);
FilterResults results = new FilterResults();
if (cursor != null) {
results.count = cursor.getCount();
results.values = cursor;
} else {
results.count = 0;
results.values = null;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Cursor oldCursor = mClient.getCursor();
if (results.values != null && results.values != oldCursor) {
mClient.changeCursor((Cursor) results.values);
}
}
}
@IgorGanapolsky
Copy link

How to use this CursorRecyclerAdapter with a Loader? Does the constructor have to be called every time onLoadFinished() is executed?

@dodushka
Copy link

Not ,you have to swapCursor(cursor) at onLoadFinished();

@sureshbora1989
Copy link

Filter is not working it this, i did like this in
cursorRecyclerAdapter.getFilter().filter(s.toString()); in TextWatcher for EditText

@Shywim
Copy link
Author

Shywim commented Dec 31, 2014

@sureshbora1989 : you need to set a FilterQueryProvider with setFilterQueryProvider before calling filter(), otherwise the Adapter does not know how to filter 😉

@icedtoast
Copy link

Nice work! @Shywim, what license is this code under? (http://choosealicense.com/)

@Shywim
Copy link
Author

Shywim commented Jan 2, 2015

@icedtoast Oops, forgot that! MIT License, edited the gist. Thanks for reminding me! 😊

@streamride
Copy link

Hi, Could you please say how to implement sevaral type of objects ( in cursor ), like in usual adapter getViewItemType() ?

@quanturium
Copy link

Be careful, this can cause a memory leak.

"This class does not implement deprecated fields and methods from CursorAdapter! Incidentally,

  • only {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER} is available, so the
  • flag is implied, and only the Adapter behavior using this flag has been ported.
    "

This is assuming the only two choices for CursorAdapter were FLAG_REGISTER_CONTENT_OBSERVER and FLAG_AUTO_REQUERY. A third choice is empty flag. When using a CursorLoader, the flag need to be set to 0 (empty flag) and not FLAG_REGISTER_CONTENT_OBSERVER as the CursorLoader register the content observer itself. If you use this class with a CursorLoader, it will leak your activity. If you are using CursorLoader, remove all the references to mChangeObserver / mDataSetObserver to prevent the leak.

@afreix
Copy link

afreix commented May 1, 2015

@quanturium Could you elaborate on what you mean by "remove all references to mChangeObserver/mDataSetObserver"?

@quanturium
Copy link

@afreix: Remove all the code that register / unregister mChangeObserver and mDataSetObserver. It is handled by the CursorLoader and therefore it is not needed here. See: https://gist.github.com/quanturium/46541c81aae2a916e31d

@klaplume
Copy link

klaplume commented May 8, 2015

Thanks for code, seems to work exactly as expected.

I'm wondering thou, if used with in conjunction with a CursorLoader, should changeCursor(Cursor) be called in the onLoadFinished and onLoaderReset callbacks? I would say yes, but I'm not 100% sure. The Cursor that will be closed in changeCursor, can not be used by another component at the same time or am I wrong?

@dekuashe
Copy link

It was mentioned earlier, but notifyItemRangeRemoved(0, getItemCount()) won't work on line 186 in swapCursor. getItemCount() will draw from the new Cursor, but the Adapter hasn't been notified that the data has changed yet. This may cause a crash (as I've seen) because the Adapter isn't being properly notified.

Just do itemCount = getItemCount() before you swap the Cursor, and then use that in notifyItemRangeRemoved instead.

@lilytea
Copy link

lilytea commented May 26, 2015

Hi , Thanks for the code. Could you let me know if I need to call any method in order to update cursor before calling notifyItemInserted(position) or notifyItemRemoved(position)? Thanks.

@hatemsh
Copy link

hatemsh commented May 26, 2015

+1 @quanturium
This did cause a memory leak for me when used with a CursorLoader. removing the observers fixed that problem.

@slidenerd
Copy link

Well here's the issue for me, I have a RecyclerView with data loaded from SQLite, now this data can be added, removed and modified, the current strategy i follow is definitely not the best where I preload all data when the activity starts and I update the database and the ArrayList separately for additions and removals, to make things worse, I have a header and footer as part of the RecyclerView, and everything is running on main thread, your solution looks good but I am afraid I will be stuck with respect to headers and footers since i need to use the position for creating them inside the onCreateViewHolder, each time an item is added, the database needs to asynchronously store the data and at the same time, the adapter's local copy of data should reflect the newest added item, same policy applies for deletion, any suggestions? thanks in advance

@AngleV
Copy link

AngleV commented Sep 19, 2015

any example how to use filtering comping two columns from database ?

@anstaendig
Copy link

How can I set this adapter to an adapterView with setAdapter()? Having a hard time understanding this :(

@jamespet77
Copy link

Is it possible to Override getItemViewType and have it work with your cursor adapter? I want to be able to change the layout base on the type of data received.


  @Override
    public int getItemViewType(int position) {
    if (mRowTypeColumn != -1) {
      return new Random().nextInt();   <- test if caused by cursor
      //return (int) getCursor().getLong(mRowTypeColumn);
    }
    return 0;
  }

  @Override
  public FavoriteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Log.d(TAG,"viewtype: " + viewType);
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_favorite, parent, false);
    return new FavoriteViewHolder(view);
  }

As long as the rowtype never changes Ihave not issues. But if I introduce types, I get an error here:

public Cursor swapCursor(Cursor newCursor) {
    if (newCursor == mCursor) {
      return null;
    }
    Cursor oldCursor = mCursor;
    if (oldCursor != null) {
      if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
      if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
    }
    mCursor = newCursor;
    if (newCursor != null) {
      if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
      if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
      mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
      mDataValid = true;
      // notify the observers about the new cursor
      notifyDataSetChanged();   <------ *HERE*
    } else {
      mRowIDColumn = -1;
      mDataValid = false;
      // notify the observers about the lack of a data set
      // notifyDataSetInvalidated();
      notifyItemRangeRemoved(0, getItemCount());
    }
    return oldCursor;
  }
    java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
     at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:2116)
     at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:4001)
     at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:9242)
     at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:5493)
     at CursorRecyclerAdapter.swapCursor(CursorRecyclerAdapter.java:186)

@hamid65217
Copy link

how to add an onClickListener to adapter? I want to have adapter positions and cursor data for clicked row.
thanks for your wonderful class :)

@ronenlh
Copy link

ronenlh commented Aug 9, 2016

@hamid65217 you probably figured it out, but what I did was a setTag() and getTag() for the itemView
This class works great!

@cbeyls
Copy link

cbeyls commented Aug 18, 2016

Here's my simpler version.

It supports stable ids by default for automatic animations and relies on an external CursorLoader to observe changes and close the cursor.

@1Riptide
Copy link

1Riptide commented Oct 9, 2016

Could you provide at least one usage example? Trying to convert a plain RecyclerView.Adapter to your implementation here, but I am having problems understanding how to use your onCreateViewHolder method to return something similar to - ViewHolder((LinearLayout)v). Not sure what I can reuse with your solution.

Updated: (Answering my own question)
Assuming you are using a subclass of this one:

public class VideoMenuCursorAdapter extends CursorRecyclerAdapter 

In your override of onCreateViewHolder(), return an instance of a class that extends RecyclerView.ViewHolder.
In my case:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.video_menu_layout_item, parent, false);

    return new VideoMenuAdapterViewHolder(v);
}

Just make sure your custom class extends RecyclerView.ViewHolder as such:

public class VideoMenuAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

@TheReprator
Copy link

TheReprator commented Oct 16, 2016

can u please provide me an example to work with filter and Loader manager with above shared gist.

@zishanj
Copy link

zishanj commented Nov 19, 2016

Any example on how to use it with SQLite db file in assets folder. I just want to retrieve it and display with RecyclerView using above CursorLoader.

@majorcoderx
Copy link

Good class

@AHMAD8088
Copy link

how to call this addapter in main activity plz help me. i m beginner

@Khodanovich
Copy link

Good afternoon. Tell me how to make a footer in your implementation of the adapter?

@inbhatt
Copy link

inbhatt commented Jul 28, 2017

Hi, Everything works fine but when I enter text to filter RecyclerView each item in the view is gone. Any ideas why this is happening?

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