how to get ID of the items in recyclerview

前端 未结 2 956
北荒
北荒 2021-01-06 17:18

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 a

相关标签:
2条回答
  • 2021-01-06 17:47

    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

    0 讨论(0)
  • 2021-01-06 17:58

    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

    0 讨论(0)
提交回复
热议问题