TrueWheel
TrueWheel

Reputation: 987

Android: Making a class parcelable

I want to pass on object between two activities in Android which has lead me to parcelable classes. I am not trying to convert my current class but don't understand the Parcelable.Creator method.

This is what I have so far

public class Account implements Parcelable{

/**
 * Declare private variables
 */

private String fName;
private String lName;
private String screenName;
private String email;
private String level;
private int userId;
//private Context myContext;

/**
 * Account constructor
 */

public Account(String fName, String lName, String sName, String email, String level, String x) throws Exception{    


    /**Parse userId into int */
    this.userId = Integer.parseInt(x);

    /**Select from DB user details */


    /**Initialize variables with results */
    this.setfName(fName);
    this.setlName(lName);
    this.setScreenName(sName);
    this.setEmail(email);
    this.setLevel(level);



}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
    // TODO Auto-generated method stub
    out.writeString(fName);
    out.writeString(lName);
    out.writeString(screenName);
    out.writeString(email);
    out.writeString(level);
    out.writeInt(userId);

}

// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Account> CREATOR = new Parcelable.Creator<Account>() {
    public Account createFromParcel(Parcel in) {
        return new Account(in);
    }

    public Account[] newArray(int size) {
        return new Account[size];
    }
};



/**
 * Getters and setters for all variables from Account class
 */

public int getUserId(){
    return userId;
}

public String getScreenName() {
    return screenName;
}

public void setScreenName(String screenName) {
    this.screenName = screenName;
}

public String getfName() {
    return fName;
}

public void setfName(String fName) {
    this.fName = fName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getLevel() {
    return level;
}

public void setLevel(String level) {
    this.level = level;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}



}

Thanks in advance.

Upvotes: 20

Views: 26129

Answers (6)

Gk Mohammad Emon
Gk Mohammad Emon

Reputation: 6938

You can create a parcelable class easily with NO HARD CODING approach and Android studio 4.1.2 can do it for you just in a few seconds !!!

Create a new parcelable class:

Step 1: Implement parcelable methods by pressing Alt+Enter for windows and Option+Enter for mac but you will find that the writeToParcel is empty for the first time -

enter image description here

Step 2: Then you will find that your class name is red now. So you need to add the CREATOR class as well as to fill the empty writeToParcel by pressing Alt+Enter for windows and Option+Enter for mac -

enter image description here

Finally, you will see your class will be a fully parcelable class now !!!

Update an existing parcelable class:

Step 1: If you need to add some new field in your existing class then you need to remove the previous writeToParcel and describeContents methods and CREATOR class and do the same steps described in the first section named Create a new parcelable class

Upvotes: 6

Bette Devine
Bette Devine

Reputation: 1194

Transferring data between activities can be done using serializable as well as Parcelable. But parcelable is considered best.(why)

There is a plugin in android that lets you insert parcelable code for fields in the class. You can find it from menu File > Settings > Plugins > Android parcelable code generator.

And use the shortcut alt + insert just like getter and setter to use the plugin.

Upvotes: 1

ingyesid
ingyesid

Reputation: 2884

Here is a great tool for Android parcelable implementations.

Parcelabler by Dallas Gutauckis

Upvotes: 24

user370305
user370305

Reputation: 109237

public static final Parcelable.Creator CREATOR =
    new Parcelable.Creator() {
        public ObjectB createFromParcel(Parcel in) {
            return new ObjectB(in);
        }

        public ObjectB[] newArray(int size) {
            return new ObjectB[size];
        }
    };

This field is needed for Android to be able to create new objects, individually or as arrays. This also means that you can use use the default constructor to create the object and use another method to hyrdate it as necessary.

Look at this Android – Parcelable

Online tool for creating Parcelable class

and http://www.appance.com/tag/parcelable/

Upvotes: 12

Michael Geier
Michael Geier

Reputation: 1843

On GitHub you can find some code I wrote some time ago for simplifying the handling of Parcelables (e.g. writing to and reading from parcels, simplifying the initializer code for CREATORs).

Writing to a parcel:

parcelValues(dest, name, maxSpeed, weight, wheels, color, isDriving);

where color is an enum and isDriving is a boolean, for example.

Reading from a parcel:

// [...]
color = (CarColor)unparcelValue(CarColor.class.getClassLoader());
isDriving = (Boolean)unparcelValue();

Creating a CREATOR for classes:

public static final Parcelable.Creator<Car> CREATOR = 
    Parceldroid.getCreatorForClass(Car.class);

...or for enums:

public static final Parcelable.Creator<CarColor> CREATOR = 
    Parceldroid.getCreatorForEnum(CarColor.class);

Just take a look at the "ParceldroidExample" I added to the project.

Upvotes: 0

micnoy
micnoy

Reputation: 3926

Here is another tool for creating parcelable objects using simple annotations

https://github.com/johncarl81/parceler

Upvotes: 4

Related Questions