zihadrizkyef
zihadrizkyef

Reputation: 1941

Set and Get item id of recycler view

I am new in RecyclerView. We can get clicked item position in RecyclerView, but can we set and get item's ID of RecyclerView? Because in my RecyclerView, the item has custom ID provided by server. I've try this code :

FragmentListProduct.java

productData = new JSONArray();
linearLayoutManager = new LinearLayoutManager(fragmentActivity);
lpAdapter = new ListProductAdapter(fragmentActivity, R.layout.list_product_grid, productData, null,
        new ListProductHolder.OnProductClickListener() {
            @Override
            public void onProductClick(View v, long id) {
                Toast.makeText(fragmentActivity, "id:"+id, Toast.LENGTH_SHORT).show();
                MainActivity.setIdToRead((int) id);
                MainActivity.replaceFragment(FragmentListProduct.this, new FragmentViewProduct());
            }
        });
rvProductList = (RecyclerView) mainView.findViewById(R.id.rvProductList);
rvProductList.setLayoutManager(linearLayoutManager);
rvProductList.setAdapter(lpAdapter);
rvProductList.setHasFixedSize(true);

ListProductHolder.java

public class ListProductHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView tvTitle;
    TextView tvPrice;
    ImageView ivImage;
    private OnProductClickListener onProductClickListener;

    ListProductHolder(View itemView, OnProductClickListener onProductClickListener) {
        super(itemView);
        this.onProductClickListener = onProductClickListener;

        tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
        ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
        tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        onProductClickListener.onProductClick(view, getItemId());
    }

    public static interface OnProductClickListener {
        public void onProductClick(View v, long id);
    }
}

ListProdutAdapter.java

public class ListProductAdapter extends RecyclerView.Adapter<ListProductHolder> {
    private Activity activity;
    private int layoutResource;
    private JSONArray productDataArray;
    private StringSignature downloadSignature;
    private ListProductHolder.OnProductClickListener onProductClickListener;

    public ListProductAdapter(Activity activity, int layoutResource, JSONArray productDataArray, StringSignature downloadSignature, ListProductHolder.OnProductClickListener onProductClickListener) {
        this.activity = activity;
        this.layoutResource = layoutResource;
        this.productDataArray = productDataArray;
        this.downloadSignature = downloadSignature;
        this.onProductClickListener = onProductClickListener;
    }

    @Override
    public ListProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(activity).inflate(layoutResource, parent, false);
        return new ListProductHolder(v, onProductClickListener);
    }

    @Override
    public void onBindViewHolder(ListProductHolder holder, int position) {...}

    @Override
    public long getItemId(int i) {
        long itemId = -1;
        try {
            itemId = productDataArray.getJSONObject(i).getInt("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return itemId;
    }
}

But when i tried it, the ID is always -1. How to solve this? or is there another solution i can do?

Upvotes: 3

Views: 20550

Answers (3)

Motee
Motee

Reputation: 112

Does the method getItemId() int ListProductAdapter have any other code? Is it same with getItemId(int i) in ListProductAdapter.In my opinion,what you need to do is just replace getItemId() with productDataArray.getJSONObject(getLayoutPosition()).getInt("id").

public class ListProductHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvTitle;
TextView tvPrice;
ImageView ivImage;
private OnProductClickListener onProductClickListener;

ListProductHolder(View itemView, OnProductClickListener onProductClickListener) {
    super(itemView);
    this.onProductClickListener = onProductClickListener;

    tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
    ivImage = (ImageView) itemView.findViewById(R.id.ivImage);
    tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
    itemView.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    onProductClickListener.onProductClick(view, productDataArray.getJSONObject(getLayoutPosition()).getInt("id"));
}

public static interface OnProductClickListener {
    public void onProductClick(View v, long id);
}

}

Upvotes: 0

Praveen
Praveen

Reputation: 737

Add click listener in the on bind view holder as view will be reused you have to set click for each view reused. Add click listener to root layout

@Override
public void onBindViewHolder(ListProductHolder holder, int position) {
    final long itemId = productDataArray.getJSONObject(position).getInt("id");

    holder.rootLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onProductClickListener.onProductClick(view, itemId);
        }
    });
}

Upvotes: 4

Anil
Anil

Reputation: 1615

You can use

itemView.setTag(your_id);

and onClick you need to use

view.getTag();

Check the below example

 public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.LogHolder>
{
    public RecyclerAdapter()
    {
    }

    @UiThread
    protected  void dataSetChanged()
    {
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        //you can pass ur server response array here
        //int count = (csMainJsonArr != null) ? csMainJsonArr.length() : 0;
        int count = 20;
        return count;
    }


    public class LogHolder extends RecyclerView.ViewHolder
    {
        TextView    nameTxt             = null;
        TextView    contactTxt          = null;
        TextView    statusTxt           = null;
        ImageView   listImg             = null;

        public LogHolder(View itemView)
        {
            super(itemView);

                nameTxt     = (TextView)itemView.findViewById(R.id.custom_NameTxt);
                contactTxt  = (TextView)itemView.findViewById(R.id.custom_ContactTxt);
                statusTxt   = (TextView)itemView.findViewById(R.id.custom_StatusTxt);
                listImg     = (ImageView)itemView.findViewById(R.id.custom_listImg);
        }
    }

    @Override
    public LogHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LogHolder holder = new LogHolder(inflater.inflate(R.layout.custom_design, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(LogHolder holder, int position)
    {
        //just get data from your json arrahy and add here
        holder.nameTxt.setText("name "+position);
        holder.contactTxt.setText("contact "+position);
        holder.statusTxt.setText("status "+position);

        //you need to set tag for holder image and holder item to get position of item
        holder.listImg.setTag(position);
        holder.itemView.setTag(position);


        holder.listImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //create your own action
                // using view.getTag() you can get the position of item clicked

                int position = (int) view.getTag();
                Log.d("=======", String.valueOf(position));
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //create your own action
                //using view.getTag() you can get the position of item clicked

                int position = (int) view.getTag();
                Log.d("=======", String.valueOf(position));
            }
        });

    }

}

and don't forget to declare this.

 csRecyclerView  = (RecyclerView) findViewById(R.id.recyclerView);
    csAdapter = new RecyclerAdapter();
    LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
    //manager.setReverseLayout(true);
    //manager.setStackFromEnd(true);
    csRecyclerView.setLayoutManager(manager);
    csRecyclerView.setAdapter(csAdapter);

Upvotes: 4

Related Questions