Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send Arraylist by Intent

How can I receive a custom ArrayList from another Activity via Intent? For example, I have this ArrayList in Activity A:

ArrayList<Song> songs;

How could I get this list inside Activity B?

like image 703
Misam Mehmannavaz Avatar asked Aug 01 '17 19:08

Misam Mehmannavaz


1 Answers

The first part to understand is that you pass information from Activity A to Activity B using an Intent object, inside which you can put "extras". The complete listing of what you can put inside an Intent is available here: https://developer.android.com/reference/android/content/Intent.html (see the various putExtra() methods, as well as the putFooExtra() methods below).

Since you are trying to pass an ArrayList<Song>, you have two options.

The first, and the best, is to use putParcelableArrayListExtra(). To use this, the Song class must implement the Parcelable interface. If you control the source code of Song, implementing Parcelable is relatively easy. Your code might look like this:

Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);

The second is to use the version of putExtra() that accepts a Serializable object. You should only use this option when you do not control the source code of Song, and therefore cannot implement Parcelable. Your code might look like this:

Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);

So that's how you put the data into the Intent in Activity A. How do you get the data out of the Intent in Activity B?

It depends on which option you selected above. If you chose the first, you will write something that looks like this:

List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");

If you chose the second, you will write something that looks like this:

List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");

The advantage of the first technique is that it is faster (in terms of your app's performance for the user) and it takes up less space (in terms of the size of the data you're passing around).

like image 126
Ben P. Avatar answered Sep 28 '22 17:09

Ben P.