Skip to content Skip to sidebar Skip to footer

How Do I Send An Array Of Objects From One Activity To Another?

I have a class like: Class persona implements Serializable { int age; String name; } And my first Activity fill an array: persona[] p; Then, I need this info in anothe

Solution 1:

AFAIK the is no method that put a serializable array into bundle any way here is a solution to use that uses parcel

change you class to this

import android.os.Parcel;
import android.os.Parcelable;

publicclasspersonaimplementsParcelable {

    int age;
    String name;

    publicstatic final Parcelable.Creator<persona> CREATOR = newCreator<persona>() {

        @Overridepublic persona[] newArray(int size) {
            // TODO Auto-generated method stubreturnnew persona[size];
        }

        @Overridepublic persona createFromParcel(Parcel source) {
            // TODO Auto-generated method stubreturnnewpersona(source);
        }
    };

    publicpersona(Parcel in) {
        super();
        age = in.readInt();
        name = in.readString();
    }

    publicpersona() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Overridepublic int describeContents() {
        // TODO Auto-generated method stubreturn0;
    }

    @OverridepublicvoidwriteToParcel(Parcel dest, int flags) {
        dest.writeInt(age);
        dest.writeString(name);

    }
}

then you can send the array like this

Bundleb=newBundle();

b.putParcelableArray("persona", p);

btw using Parcelable instead of Serializable is more efficient in Android

Solution 2:

You class will need to implement Parcelable. Then, you can send it in a bundle by using the Bundle.putParcelableArray()-method.

Also, a general advice: Class names should always start uppercase

Post a Comment for "How Do I Send An Array Of Objects From One Activity To Another?"