shontauro
shontauro

Reputation: 1822

How can i pass a list of objects (any object), through bundle, from activity A to Activity B?

This is on the android platform, i have a list of objects of type (FitItem), and i want pass the list from my activity A to another activity B, and on the activity B i want get the list of objects again

Upvotes: 0

Views: 4555

Answers (5)

Dhara Jani
Dhara Jani

Reputation: 461

Implements Serializable in model class. Then you can pass model class using bundle/intent.

Upvotes: 0

Heitor Colangelo
Heitor Colangelo

Reputation: 516

You must serialize your object.

"Seriawhat?"
Ok, first things first: What is object serialization?

"Got it, but how do I do that?"
You can use Parcelable (more code, but faster) or Serializable (less code, but slower).
Parcelable vs Serializable.

"Save me some time, show me the code!"
Ok, if you'll use Parcelable, see this.

And if you'll use Serializable, see this and/or this.

Hope that helps!

Upvotes: 1

bschultz
bschultz

Reputation: 4254

Intent yourIntent = new Intent(activityA.this, activityB.class);
Bundle yourBundle = new Bundle();
yourBundle.putString("name", value);
yourIntent.putExtras(yourBundle);
startActivity(yourIntent);

And you get the value in the next Activity (in your onCreate()):

Bundle yourBundle = getIntent().getExtras();
String s = yourBundle.getString("name");

This example is passing a String, but you should be able to grasp how to use it for other objects.

Upvotes: 2

ccheneson
ccheneson

Reputation: 49410

For custom classes: You will have to have your FitItem class implements Parcelable.

Then in Activity A, from an Intent object, use putParcelableArrayListExtra to pass the list of FitItem to Activity B and in your Activity B, use getParcelableArrayListExtra to retrieve the list of FitItem

If you want to pass list of String, Integer, Float ..., refer to bschultz post

Upvotes: 1

Krylez
Krylez

Reputation: 17820

If they're if the object is serializable, just add them as extras to the intent. I think something like this:

// in Activity A, when starting Activity B
Intent i = new Intent(this, ActivityB.class);
i.putExra("fitItemList", fitItemList);
startActivity(i);

// in Activity B (onCreate)
ArrayList<FitItem> fitItemList = savedInstanceState.getSerializableExtra("fitItemList");

edit: Just like bschultz already posted :)

Upvotes: 0

Related Questions