Parcel vs. Serializable用于在服务/活动之间交换对象

时间:2011-01-05 18:41:55

标签: android serialization location parcelable

让我先说明一下:我正在开发一个基于位置的应用程序,它在几个活动和服务中调用对象的不断重新创建和交换。创建正在交换的对象的必要数据存储在SQLite数据库中,然后通过从远程SQL数据库检索数据来填充。

很明显,将对象的原始属性传递给活动/服务(通过意图)是一个巨大的编码开销,减少了应用程序可能具有的每个扩展前景。所以,很快我决定扩展我的主对象类来实现Parcelable,如下所示:

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(){
        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

虽然我检查了包裹字段的每个数据条目,但以下异常会一直产生:

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

出于这个原因,我考虑实现serializable的MyProduct.class,希望它将变成一个更容错的结构。在上述情况下,这种交替的利弊是什么?

0 个答案:

没有答案