0

如其他地方所述;Android活动之间传递实例的方式,要么使传递的对象实现可序列化的接口,要么实现可打包的接口。在我看来,只要您的 Android 应用程序旨在显示您的狗的年龄和姓名,这很好。在不使用静态引用的情况下使用稍微高级的对象是有问题的。

要传递的对象正在使用例如外部库来实现其目的。为了使所有使用的类(包括库中的类)能够进行序列化,需要声明此接口,否则 Android 将抛出运行时 IOException,说明对象无法序列化(某些东西不是隐含的可序列化接口或没有无参数)构造函数)。因此,我猜想,可序列化的工作方法需要重新编译库。Parcel 方法需要将对象的字段写入某些输出。此输出支持自定义对象,但传递对象(包括库)再次需要实现可序列化接口才能工作。

使用外部库传递实例的解决方案是什么?

4

1 回答 1

0

One of the approaches is to implement Serializer class for each not Serializable type you wants to pass between activities. Here is a simple Serializer interface:

public interface Serializer {
    void serialize(Object object, DataOutputStream out);

    Object deserialize(DataInputStream in);
}

After that you can use this or any other Base64 encoder/decoder to convert DataOutputStream to String or other serializable type. Use for this purposes methods like:

private String serializeToString(Object object, Serializer serializer) {
    ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    DataOutputStream dStream = new DataOutputStream(bStream);

    try {
        serializer.serialize(object, dStream);
    } catch (IOException e) {
        logger.error(e, "Couldn't serialize " + object);
        return null;
    }

    return Base64.encodeToString(bStream.toByteArray(), false);
}

private Object deserializeFromString(String string, Serializer serializer) {
    try {
        return serializer.deserialize(
                new DataInputStream(
                        new ByteArrayInputStream(
                                Base64.decode(string))));
    } catch (IOException e) {
        logger.error(e, "Couldn't deserialize [" + string + "]");
        return null;
    }
}

After that you can simply pass your object through activities serialized as String and simply deserialize it back to your object when you need.

于 2012-04-26T11:14:39.353 回答