简体   繁体   中英

RecyclerView passing data via Intent extras

So I'm trying to pass some data via Intent extras to the second activity. This code worked fine with ListView, but now when I switched to RecyclerView it doesn't show any text, text area is blank.

Here's the code: (starting in onBindViewHolder())

 holder.container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passData();
            }
        });

    }

    private void passData() {
        Todo item = new Todo();
        Intent i = new Intent(c, Details.class);
        i.putExtra("nazivTodoa", item.getTitle());
        i.putExtra("datumTodoa", item.getRecordDate());
        i.putExtra("idTodoa", item.getItemId());
        c.startActivity(i);
    }

And this is how I get in in second activity:

  Bundle extras = getIntent().getExtras();
    String naslov = extras.getString("nazivTodoa");
    String datum = extras.getString("datumTodoa");

    textViewNazivTodoaDetails.setText(naslov);
    textViewDatumTodoaDetails.setText(datum);

What am I doing wrong?

What you are doing wrong, is you are not getting the current object that is clicked on. You do that by getting your object from the arraylist you use in your adapter. Do it like that:

Arraylist<Item> yourlist = new Arraylist();

       @Override 
        public void onClick(View v) {
            // position = pass the current position of the object you want
            passData(int position);

        } 
    }); 

} 

private void passData(int position) { 
    Todo item = new Todo();
    Intent i = new Intent(c, Details.class);
    i.putExtra("nazivTodoa", yourlist.get(position).getTitle());
    i.putExtra("datumTodoa", yourlist.get(position).item.getRecordDate());
    i.putExtra("idTodoa",    yourlist.get(position).item.getItemId());
    c.startActivity(i);
} 

Like dymmeh said, you need to pass the item in the list to the new activity. You are currently passing a newly created empty object.

Instead of

Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());

You should have

Todo item = listData.get(itemPosition);
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());

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