Parcel vs. Serializeable for exchanging objects among services/activities
Let me first give you the whole picture: I am developing a location based application, that invokes a constant recreation and exchange of objects, among several activities and services. The necessary data to create the objects being exchanged, is stored in an SQLite database, that in its turn gets populated by retrieving data from a remote SQL database.
It got quickly obvious, that passing raw attributes of an object to activities/services (via intents), was a huge coding overhead, diminishing every extension prospects the application might have. So, soon i decided to extend my main object class to implement a Parcelable one, as shown below:
public class MyProduct implements Parcelable {
//MyProduct Attributes
private int myProductId;
private String myProductDescription;
private float myProductRadius;
//More attributes...
public MyProduct() {
myProductId=-1;
myProductDescription="defaultProductDescription";
myProductRadius=10;
//More attributes
}
public int describeContents开发者_JAVA百科(){
return 0;
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags){
//Product attributes
try{
out.writeInt(myProductId);
out.writeString(myProductDescription);
out.writeFloat(myProductRadius);
//More attributes
}
catch (Exception e){}
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyProduct> CREATOR = new Parcelable.Creator<MyProduct>() {
//public class MyCreator implements Parcelable.Creator<MyProduct> {
public MyProduct createFromParcel(Parcel in) {
return new MyProduct(in);
}
public MyProduct[] newArray(int size) {
return new MyProduct[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyProduct(Parcel in) {
//in.readParcelable(MyProduct.class.getClassLoader());
try{
//MyProduct.class.getClassLoader();
myProductId=in.readInt();
myProductDescription=in.readString();
myProductRadius=in.readFloat();
//More attributes
}
catch(Exception e){}
}
//Setters and Getters
}//endOfMyProduct.class
Although i checked every data entry to the parcel fields, the following exception keeps spawning:
01-05 19:35:11.570: ERROR/Parcel(59): Class not found when unmarshalling: com.nifo.distribution.MyProduct, e: java.lang.ClassNotFoundException: com.nifo.distribution.MyProduct
For this reason, i consider of the MyProduct.class implementing serializable, hoping that it will turn to be a more error-forgiving structure. What would be the pros and cons of such alternation in the case described above?
精彩评论