Android NotSerializableException为对象引发

Sam*_*age 5 java serialization android

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

public class MyDevice implements Serializable {}
Run Code Online (Sandbox Code Playgroud)

但是在应用程序开始时,它反序列化并存储在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;
}
Run Code Online (Sandbox Code Playgroud)

我的序列化代码

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

而我将其称为如下.

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

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

java.io.WriteAbortedException: Read an exception; 
java.io.NotSerializableException: com.geotracker.entity.MyDevice
Run Code Online (Sandbox Code Playgroud)

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

Dur*_*dal 4

Android 对象似乎不可Context序列化。您可以通过将对象声明为瞬态来解决此问题Context,您可以在 JDK 规范中阅读有关该对象的信息:链接。基本上将字段标记为瞬态意味着它不会参与序列化

因此,在以下位置声明您的字段MyDevice

private transient Context context;

你应该可以走了!