Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make CursorAdapter be set in recycleview, just like ListView?

I didn't google out a solution till now to replace listview in my project, because I need to use the cursor linked with the sqlite.

Old way as followed: listview.setAdapter(cursorAdapter) in this way, I can get the cursor to deal with data in database

but now, recycleview.setAdapter(recycleview.adapter) it doesn't recognize the adapter extending BaseAdapter

so anyone can give me a hand?

like image 445
machinezhou Avatar asked Oct 11 '14 07:10

machinezhou


People also ask

When to use Recycler view?

Android recyclerview is the most advanced version of the listview. basically, an android listview is used to present a simple data set. if you want to display large data set in your app, you should use recyclerview.

What is itemview in RecyclerView?

A ViewHolder describes an item view and metadata about its place within the RecyclerView. RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive View. findViewById(int) results.

Why does a RecyclerView need an adapter?

RecyclerView. Adapter base class for presenting List data in a RecyclerView , including computing diffs between Lists on a background thread. Adapters provide a binding from an app-specific data set to views that are displayed within a RecyclerView .


Video Answer


1 Answers

Implementing it yourself is actually quite simple:

public class CursorAdapter extends RecyclerView.Adapter<ViewHolder>{

    Cursor dataCursor;

    @Override
    public int getItemCount() {
        return (dataCursor == null) ? 0 : dataCursor.getCount();
    }


    public void changeCursor(Cursor cursor) {
        Cursor old = swapCursor(cursor);
        if (old != null) {
          old.close();
        }
      }

     public Cursor swapCursor(Cursor cursor) {
        if (dataCursor == cursor) {
          return null;
        }
        Cursor oldCursor = dataCursor;
        this.dataCursor = cursor;
        if (cursor != null) {
          this.notifyDataSetChanged();
        }
        return oldCursor;
      }

    private Object getItem(int position) {
        dataCursor.moveToPosition(position);
        // Load data from dataCursor and return it...
      }

}
like image 97
Nyx Avatar answered Sep 23 '22 07:09

Nyx