How to pass ArrayList<CustomeObject> from one activity to another?

DCoder picture DCoder · Jan 21, 2014 · Viewed 121.9k times · Source

I want to send Following ArrayList from one activity to another please help.

ContactBean m_objUserDetails = new ContactBean();
ArrayList<ContactBean> ContactLis = new ArrayList<ContactBean>(); 

I am sending the above arraylist after adding data in it as follows

  Intent i = new Intent(this,DisplayContact.class);
  i.putExtra("Contact_list", ContactLis);
  startActivity(i);

But I am getting problem while recovering it.

ArrayList<ContactBean> l1 = new ArrayList<ContactBean>();
Bundle wrapedReceivedList = getIntent().getExtras();
l1= wrapedReceivedList.getCharSequenceArrayList("Contact_list");

At this point I am getting this error:

Type mismatch: cannot convert from ArrayList<CharSequence> to ArrayList<ContactBean>

My ContactBean class implements Serializable please also tell why we have to implement serializable interface.

Answer

Ravind Maurya picture Ravind Maurya · Jan 21, 2014

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");