how to get ID of the items in recyclerview

13,912

Solution 1

Create this method in your adapter to the get id of that specific object and pass the id to the delete the fuction of DbHelper class.

int getId(int position){
    return data.get(position).ID;
}

And avoid accessing the members of a class directly. Instead of that you can use getter and setter methods.

And for updating the recyclerview after adding new data you can call notifyDataSetChanged() in the respective insert method in your adapter.

EDIT:

To add a new element into your recycler view add this method in your adapter

void addItem(Informationn infoObj){
     data.add(infoObj);
     notifyDataSetChanged();
}

Call this method using your adapter object and pass the new item as parameter and your recyclerview will be updated with the new items

Solution 2

Use the getItemId method if you have overridden it in yr adapter like so

@Override
     public long getItemId(int position) {
         return yrModel.getId();
       }

    yrViewHolder.idTv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Long id = yrList.get(position).getId();

            Log.e(TAG, "List item ID: " + id);
        }
    });

That way u get the item position and the ID using the getItemId method

Share:
13,912
Anshul..
Author by

Anshul..

Updated on June 27, 2022

Comments

  • Anshul..
    Anshul.. almost 2 years

    i'm using slide to delete from recyclerview but the problem comes when getAdapterPosition() doesn't match with the row_id of sql table. how can i get id from the adapter and how to update recyclerview when the data is added(it doesn't display new data until i reopen the app or change orientation) ?

    public class MainActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;
    MyAdapter myAdapter;
    ImageButton floatButton;
    
    DbHelper dbHelper;
    
    ArrayList<Information> data;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
        floatButton = (ImageButton) findViewById(R.id.imageButton);
        floatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddDetailPage.class);
                MainActivity.this.startActivity(intent);
            }
        });
    
    
        dbHelper = new DbHelper(this);
    
        data = new ArrayList<>();
    
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        myAdapter = new MyAdapter(this, showData());
    
    
        mRecyclerView.setAdapter(myAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    
    
        ItemTouchHelper helper = new ItemTouchHelper(createHelperCallback());
        helper.attachToRecyclerView(mRecyclerView);
    }
    
    private ItemTouchHelper.Callback createHelperCallback() {
        ItemTouchHelper.SimpleCallback simpleItemCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT |
                ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }
    
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                deleteItem(viewHolder.getAdapterPosition());
            }
        };
        return simpleItemCallback;
    }
    
    
    public ArrayList<Information> showData() {
        Cursor res = dbHelper.showData();
        while (res.moveToNext()) {
            Information information = new Information();
            information.ID = res.getString(0);
            information.first = res.getString(0);
            information.second = res.getString(2);
            information.detail = res.getString(3);
            data.add(information);
        }
        return data;
    }
    
    public void deleteItem(int position){
        DbHelper dbHelper = new DbHelper(this);
        dbHelper.delete(position);
    
    
        myAdapter.notifyItemRemoved(position);
    
        myAdapter.delete(position);
    }
    

    }

    public class MyAdapter extends RecyclerView.Adapter {

    private MainActivity mainactivity;
    private ArrayList<Information> data;
    private LayoutInflater layoutInflater;
    
    public MyAdapter(MainActivity mainActivity, ArrayList<Information> information) {
        this.mainactivity = mainActivity;
        this.data = information;
        layoutInflater = LayoutInflater.from(mainActivity);
        notifyDataSetChanged();
    }
    
    
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.list_item, parent, false);
        return new ViewHolder(view, data);
    }
    
    
    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        holder.first.setText(data.get(position).first);
        holder.second.setText(data.get(position).second);
        holder.detail.setText(data.get(position).detail);
    
    }
    
    @Override
    public int getItemCount() {
        return data.size();
    }
    
    public class ViewHolder extends RecyclerView.ViewHolder{
    
        TextView first, second, detail;
        ArrayList<Information> info;
    
    
        public ViewHolder(View itemView, ArrayList<Information> data) {
            super(itemView);
    
            this.info = data;
    
            first = (TextView) itemView.findViewById(R.id.firstText);
            second = (TextView) itemView.findViewById(R.id.secondText);
            detail = (TextView) itemView.findViewById(R.id.detail);
        }
    
    }
    
    public void delete(int x){
        data.remove(x);
        notifyDataSetChanged();
    }
    

    }

    public class DbHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "students.db";
    public static final String TABLE_NAME = "student_table";
    public static final String ID = "_id";
    public static final String FIRST_NAME = "first_name";
    public static final String SECOND_NAME = "second_name";
    public static final String DETAIL = "detail";
    
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "( " + ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + FIRST_NAME + " TEXT ," + SECOND_NAME + " TEXT ," + DETAIL + " TEXT );");
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
    
    public boolean insertData(String first, String second, String detail) {
        SQLiteDatabase db = this.getWritableDatabase();
    
        ContentValues contentValues = new ContentValues();
        contentValues.put(FIRST_NAME, first);
        contentValues.put(SECOND_NAME, second);
        contentValues.put(DETAIL, detail);
        long x = db.insert(TABLE_NAME, null, contentValues);
    
        if (x == -1) {
            return false;
        } else {
            return true;
        }
    
    
    }
    
    public Cursor showData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        return res;
    }
    
    public void delete(int x) {
        int y = x + 1;
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, ID + "=" + y, null);
    }
    

    }

  • Anshul..
    Anshul.. about 7 years
    thanks Ranjan, i'd set the getter but i didn't put ".ID" at the end so it was returning an object but i'm still stuck at notifyDataSetChanged()
  • pskink
    pskink about 7 years
    no need for such method, just override getItemId()
  • Ranjan
    Ranjan about 7 years
    add a method for adding new element in your adapter
  • Anshul..
    Anshul.. about 7 years
    i'm really not able to do it ! can you help some more giving how to do it from insertData() in DbHelper class ?
  • pskink
    pskink about 7 years
    @Anshul.. just call changeCursor / swapCursor methods
  • Anshul..
    Anshul.. about 7 years
    @pskink it works but i'm not able to understand what's going on behind it and i don't want to copy paste next time i make something similar, it's been five days that i started with android studio and i'd like to know how it works, the method Ranjan wrote, it's simple and i want to know more about where to call this method or something similar to it.
  • pskink
    pskink about 7 years
    @Anshul.. no its not simple, when your data model is Cursor based you should use a "Cursor" based adapter like CursorRecyclerAdapter - next time you will just update onBindViewHolderCursor() method, that's all - also it gives you "out of the box" list filtering and provides valid database IDs
  • AJW
    AJW over 5 years
    @Ranjan K.M. I have a similar list of RecyclerView items. How can I save the Adapter positions for the entire dataset of items to my SQLite database? I am trying to save the order of the items shown in the list. I'd like to save the positions when the Activity is finished or the user exits the app so the positions can be re-used when the user navigates back to the Activity or re-opens the app. That way the user sees the same order of items again.