Daniele Daniele - 4 months ago 15
Java Question

How to pass a single ArrayList elements to another Activity

I have got an ArrayList that looks something like this:

list = new ArrayList<Obj>();

list.add(new Obj(R.drawable.img, "string", "na, na, na"));
list.add(new Obj(R.drawable.ima2, "string 2", "Na, na, na"));
list.add(new Obj(R.drawable.img3, "string 3", "Na, na, na"));
...


this List inflates into a
RecyclerView
when I click a
RecyclerView
Item, I want to pass only the element of the list I have clicked on to another Activity, not the whole List.

How do I do it?

I appreciate if you could help me out!

this is what I tried but I think it passes the whole List:

ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener(){
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
Intent intent = new Intent(ChordsListActivity.this, ChordActivity.class);
intent.putExtra("selected", list);
startActivity(intent);
}
});

Answer

How to pass a single ArrayList elements to another Activity

For passing custom object to next Activity do following:

1. Make sure custom object class implementing Serializable or Parcelable(recommended to use) interface.

2. Use Bundle.putSerializable if implementing Serializable or use Bundle.putParcelable if implementing Parcelable interface.

Using Serializable:

Bundle bundle=new Bundle();
bundle.putSerializable("selected", chords.get(position));
intent.putExtra(bundle);

3. In next Activity use Bundle. getSerializable for getting selected object:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
Obj selectedObj=(Obj)bundle.getSerializable("selected");