【问题标题】:Android NotSerializableException raises for an objectAndroid NotSerializableException 引发对象
【发布时间】:2014-01-31 19:41:56
【问题描述】:

在我的 android 应用程序中,我使用 文件来存储许可证数据。我使用序列化对象。我创建了一个 Device 对象并将文件详细信息读入该对象。 设备类实现 Serializable

public class MyDevice implements Serializable {}

但在应用程序开始时,它反序列化并存储在 MyDevice 对象中。我的 deserializeObject 方法如下。

public MyDevice deserializeObject() {

    File SerialFile = new File(GeoTrackerPaths.FILE_PATH);
    MyDevice AndDeviceIn = new MyDevice();

    if (SerialFile.exists()) {
        try {
            FileInputStream fileIn = new FileInputStream(GeoTrackerPaths.FILE_PATH);
            ObjectInputStream objInput = new ObjectInputStream(fileIn);
            AndDeviceIn = (MyDevice) objInput.readObject();
            objInput.close();
            fileIn.close();

        } catch (Exception e) {

            Log.i("TAG", "Exception during deserialization:" + e.getMessage());
            e.printStackTrace();
            System.exit(0);
        }
    }

    return AndDeviceIn;
}

我的序列化代码

public void serializeObject(Context context, String phoneModel,
        String androidVersion, String executiveCode, String Key,
        String modelID, String tempKey, int noLogin, String expireDate, String Status) {

    try {
        MyDevice AndDeviceOut = new MyDevice(context, phoneModel,
                androidVersion, new Date(), executiveCode, Key, modelID,
                tempKey, noLogin, expireDate, Status);

        FileOutputStream fileOut = new FileOutputStream(
                GeoTrackerPaths.FILE_PATH);
        ObjectOutputStream objOutput = new ObjectOutputStream(fileOut);
        objOutput.writeObject(AndDeviceOut);
        objOutput.flush();
        objOutput.close();
        fileOut.close();

    } catch (Exception e) {
        Log.i("TAG", "Exception during serialization:" + e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }
}

我这样称呼它。

DeviceActivator activate=new DeviceActivator();
activate.serializeObject(Activation.this, phoneModel, androidVersion, txtExe, exeKey, modeilID, tempKey, noLogin, expireDate, Activation_Status);

当我运行应用程序时,会引发以下异常。

java.io.WriteAbortedException: Read an exception; 
java.io.NotSerializableException: com.geotracker.entity.MyDevice

我该如何解决这个问题?

【问题讨论】:

  • 与异常无关,但为什么要创建新的 MyDevice 对象,然后将相同的引用分配给从文件中读取的对象?
  • 你的意思是“MyDevice AndDeviceIn = new MyDevice();”不是吗。我不应该创建一个 MyDevice 实例来存储对象............
  • 您的示例反序列化代码看起来没有问题,可能是您执行序列化过程的代码存在问题。你能把那部分也发一下吗?
  • 好的,我会发布序列化部分......
  • 我不相信 Android Context 对象是可序列化的。尝试删除它并再次运行该过程以查看是否是问题

标签: java android serialization


【解决方案1】:

看起来 Android Context 对象不是可序列化的。您可以通过将 Context 对象声明为瞬态来解决此问题,您可以在 JDK 规范的此处阅读:Link。基本上将字段标记为瞬态意味着它不会参与序列化

所以在MyDevice 中这样声明你的字段:

private transient Context context;

你应该很高兴!

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2014-09-02
    • 2015-12-11
    • 2015-06-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2015-02-27
    相关资源
    最近更新 更多