0

我有一个包含许多常见对象的外部 Java 库(即用户的姓名、姓氏、地址......)。我想要构建的东西是一个(反)序列化器类,它将我的所有对象转换为 Parcelable 对象以使用 Intents 发送。问题是 Android 的意图不支持 putExtra(String,Parcel) 或类似的东西。你知道如何克服这种不便吗?实际上,我将所有实例都放在 Application 类中,但我认为这是一种肮脏的方法……更干净的方法?

4

2 回答 2

2

您可以使用Intent 的putExtras(Bundle extras)方法并在您的类方法exportToBundle()中实现,该方法返回带有该对象值的Bundle 。如果您不想在您的类中创建任何其他方法,您可以使用静态方法创建另一个实用程序类,该方法将您的类的对象转换为 Bundle。如果你的类是Parcelable你可以直接把它放到Bundle usingputParcelable(String key, Parcelable value)方法中。

于 2014-02-17T16:42:29.627 回答
0

您可以直接将 Parcelable 类放入意图中,以便支持您正在寻找的内容。这里有一个警告,我认为你已经通过提到序列化/反序列化来理解这个概念。您正在发送该类的副本,该副本将由处理意图的类重建。 官方的 android 示例很弱,因为只发送了一个整数,我们已经可以做到这一点。

传递类的示例意图

        Intent intent = new Intent(context, TheClassImCalling.class);
            // use a constant that's public or an R string so both the sender
            // and receiver are working on the same class
            // the class you are sending goes into the putExtra method statement.
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
    mKmlSummary);
    startActivity(intent);

您使用与发送它相同的常量使用这样的语句从类中提取副本。

KMLSummary mkmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

以下是必须实现的方法

public class KmlSummary implements Parcelable {

// 以 Parcel 作为参数的构造函数。// 您以相同的顺序读取和写入值。

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
            in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
    this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}


// Overridden methods for the Parseable interface.
@Override
 public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
     arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
     arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
     arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
     arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
     arg0.writeString(s);
 }

@Override
 public int describeContents() {
    //
     return 0;
 }


    // Some glue to tell the OS how to create the class from the parcel
@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
     public KmlSummary createFromParcel(Parcel in) {
        return new KmlSummary(in);
     }

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

就是这样,您可以将类序列化为意图并从意图中反序列化类。

祝你好运丹尼117

于 2014-02-17T17:52:10.717 回答