androidlistviewandroid-intentarraylist

Passing a List from one Activity to another


How to pass Collections like ArrayList, etc from one Activity to another as we used to pass Strings, int with help of putExtra method of Intent?

Can anyone please help me as i want to pass a List<String> from one Activity to another?


Solution

  • 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");
    

    Please note that serialization can cause performance issues: it takes time, and a lot of objects will be allocated (and thus, have to be garbage collected).