NewBIe
NewBIe

Reputation: 299

Implement cursor into the recyclerview adapter

I am currently working on an android app that feeds my content activity with data from the local database. I am using RecycleView and Cardview with a local database.

I have implemented recycleview adapter but my cursor adapter to the recycle view adapter fails when with a return problem. I think i am not doing something right. What I have tried so far is below.

The code below is suppose to set data from the database handler,

public class Items extends Activity{

static Context context;
private String name;
  public void setName(String name){
    this.name=name;
  }
  public String getName(){
    return name;
  }
    private static DatabaseHandler db = new DatabaseHandler(context);

      public static Items fromCursor(Cursor cursor) {
          ArrayList<String> users;
                 users = new ArrayList<String>();
                 users = db.AllItems();
                return users;
      }

}

Also the bind view holder class which is in the recyleview

 public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
    Items myListItem = Items.fromCursor(cursor);
    viewHolder.mTextView.setText(myListItem.getName());

}

And lastly, the get all items from the database handler

    public ArrayList<String> AllItems() {
        ArrayList<String> user = new ArrayList<String>();

        // Select All Query 
        String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                String firstName = c.getString(c.getColumnIndex(KEY_FIRSTNAME));

                user.add("" + firstName );
            } while (c.moveToNext());
        }
        return user;
    }

I am finding it difficult to implement the cursor or data to the onBindViewHolder method through the Items class. I would be grateful if someone could help me fix it. I am most grateful.

Upvotes: 1

Views: 2731

Answers (1)

tochkov
tochkov

Reputation: 3020

There is a cleaner way to implement Cursor with RecyclerView.

Create YourAdapter extending CursorRecyclerAdapter - you will have all RecyclerView.Adapter functionalities alongside swapCursor(), changeCursor() and a constructor with Cursor parameter.

If you really need a custom implementation you can use the class above for a start.

For a better way to obtain the cursor I recommend looking at how to Run a Query with a CursorLoader

Upvotes: 1

Related Questions