简体   繁体   中英

Sending variable from Adapter to Activity

In my app I use a CardView . When a card is clicked, another activity opens which needs the id of the card. So I tried to send the data through the intent which I'm using to open the activity as well. My problem is that the received value in the receiving class always stays 0 , although the shared value is different. Am I getting it wrong?

The part of the adapter:

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {

    final int a = dataAdapter.getId();

    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(context, ChatActivity.class);
            intent.putExtra("CardID", a);
            context.startActivity(intent);
        }
});

The second class that gets the value:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_layout);

        Intent intent = getIntent();
        int cardId = intent.getIntExtra("cardID", 0);
        Log.d("cardId = ", String.valueOf(cardId)); 
}

当u插入时,CardID“ C”为大写,而当插入u时,cardID“ c”为小写。区分大小写只需使其大小写相同即可。

Replace with this -

intent.getIntExtra("CardID", 0);

Capital C is missing.

If your dataAdapter is a list, you can use position param in onBindViewHolder() .

intent.putExtra("CardID", dataAdapter.get(position));

or you can use getAdapterPosition() only if you use recyclerViewAdapter

intent.putExtra("CardID", dataAdapter.get(getAdapterPosition()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM