微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Android NotSerializableException为一个对象引发

在我的Android应用程序中,我使用文件来存储许可证数据.我使用Serialize对象.我创建一个Device对象并将文件详细信息读入该对象. 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,txtExe,exeKey,modeilID,Activation_Status);

当我运行应用程序时,会引发异常.

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

我怎样才能解决这个问题?

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

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

私有瞬态上下文;

你应该好好去!

原文地址:https://www.jb51.cc/android/430993.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐