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?
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?
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 anIntent
is available here: https://developer.android.com/reference/android/content/Intent.html (see the variousputExtra()
methods, as well as theputFooExtra()
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, theSong
class must implement theParcelable
interface. If you control the source code ofSong
, implementingParcelable
is relatively easy. Your code might look like this:The second is to use the version of
putExtra()
that accepts aSerializable
object. You should only use this option when you do not control the source code ofSong
, and therefore cannot implementParcelable
. Your code might look like this:So that's how you put the data into the
Intent
in Activity A. How do you get the data out of theIntent
in Activity B?It depends on which option you selected above. If you chose the first, you will write something that looks like this:
If you chose the second, you will write something that looks like this:
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).
I hope this helps you.
1. Your Song class should be implements Parcelable Class
2. Put your arraylist to putParcelableArrayListExtra()
3. In the ActivityB
Misam is sending list of Songs so it can not use plain
putStringArrayList()
. Instead, Song class has to implement Parcelable interface. I already explained how to implement Parcelable painless in post here.After implementing Parcelable interface just follow Uddhavs answer with small modifications:
Please note, bundle is one of the key components in Android system that is used for inter-component communications. All you have to think is how you can use put your Array inside that bundle.
Sending side (Activity A)
/* Note: you have to use writeToParcel() method to write different parameters values of your Song object */
Receiving side (Activity B)