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.
Here is a great tool for Android parcelable implementations.
Parcelabler by Dallas Gutauckis
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With