Unable to pass Recycleview position to another activity

Viewed 31

I am building an expense tracker app. I got stuck in a problem where I couldn't pass my adapter position to another activity. The thing that bothers me more that I am able to pass my id from adapter to activity but couldn't pass the position. I have pasted the code below for better understanding. Can someone help me on this?

public void onBindViewHolder(@NonNull UltAdapter.MyViewHolder holder, int position) {
        TransactionModel MyModel = myViewsList.get(position);
        Log.d("checkTag -> ", MyModel.getType());
        holder.amount.setText(MyModel.getAmount());
        if(Objects.equals(MyModel.getType(), "Income"))
        {
            holder.amount.setTextColor(Color.GREEN);
            holder.priority.setBackgroundResource(R.drawable.mark);
        }
        else
        {
            holder.amount.setTextColor(Color.RED);
            holder.priority.setBackgroundResource(R.drawable.redmark);
        }
        final int pos = holder.getAdapterPosition();
        holder.date.setText(MyModel.getDate());
        holder.note.setText(MyModel.getNote());
        holder.Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context,Update_transaction.class);
                i.putExtra("key",myViewsList.get(pos).getId());
                i.putExtra("pos",pos);
                context.startActivity(i);

            }
        });
    }
2 Answers

I've seen your previous question where you are retrieving data like this :

Bundle bundle = getIntent().getExtras();
    Update_db = new DataSaver(this);
    if(bundle != null)
    {
        id = bundle.getString("key");
        pos = bundle.getString("pos");
        Toast.makeText(this, "pos : " + pos, Toast.LENGTH_SHORT).show();
    }

Instead Did you tried to get data like this :

int pos = getIntent().getIntExtra("pos", -1 /* default value */)

and For key I assume that your key is a string

String key = getIntent().getStringExtra("key");

I had this probleme before, the Type of position is an Int, and in retreiving it's suppose to be a String, so there is a solution In passing data :

            Intent i = new Intent(context,Update_transaction.class);
            i.putExtra("key",myViewsList.get(pos).getId());
            i.putExtra("pos",String.valueOf(pos));
            context.startActivity(i);

In retreiving data:

            int pos;
            id = bundle.getString("key");
            pos = Integer.parseInt(bundle.getString("pos"));
Related