Daniele Daniele - 2 months ago 7
Android Question

How to pass a single ArrayList<CustomObj> elements to another Activity

You've got an ArrayList for example:

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?

This is what I have tried so far:

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.putExtras(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");
Comments