Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass an object array to an Activity?

I have read posts on passing arrays from and to activities, but I am confused as to how I would do it for my specific case.

I have an array of objects called DaysWeather (a DaysWeather[] array) where the objects have several String attributes as well as a bitmap attribute. I read somewhere that you have to make it serializable or parceable or something, but it seems messy at first glance.

Could someone lead me in the right direction?

Is there a simple way to do this?

like image 491
joepetrakovich Avatar asked Nov 15 '10 06:11

joepetrakovich


People also ask

How do you pass an array of objects?

To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

How do you pass an object through intent?

One way to pass objects in Intents is for the object's class to implement Serializable. This interface doesn't require you to implement any methods; simply adding implements Serializable should be enough. To get the object back from the Intent, just call intent. getSerializableExtra .


1 Answers

Your objects need to implement the Parcelable interface.

When this is done, you can create the Parcelable array and pass it to the activity:

// We assume we have an array: DaysWeather[] input;
Parcelable[] output = new Parcelable[input.length];
for (int i=input.length-1; i>=0; --i) {
    output[i] = input[i];
}

Intent i = new Intent(...);
i.putExtra("myArray", output);

Also note that when you implement the Parcelable interface, do not serialize full heavy objects. For instance, for your bitmap, serialize the ressource ID only and when inflating, recreate the bitmap from the ressource ID.

like image 137
Vincent Mimoun-Prat Avatar answered Sep 20 '22 20:09

Vincent Mimoun-Prat