无法序列化对象并在Android中将其恢复

时间:2013-12-16 15:37:03

标签: android fileoutputstream

我正在尝试对一个Enum类进行serlize,这样我就可以在onCreate()方法中恢复,所以每次运行我都有一个更新的类。

以下是对类进行serlizing和反序列化的代码:

private void serializeModulesManager() {
    try {
        FileOutputStream fos = openFileOutput("modules.ser",
                Context.MODE_PRIVATE);
        ObjectOutputStream out = new ObjectOutputStream(fos);
        out.writeObject(Module.values());
        out.close();
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void restoreModulesManager() {
    FileInputStream fileIn;
    Module[] arr = null;
    try {

        fileIn = openFileInput("modules.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        arr = (Module[]) in.readObject();

        for (Module c : arr) {
            Module.valueOf(c.name()).serilize(c);
        }

        in.close();
        fileIn.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (StreamCorruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我在onDestroy()中调用serializeModulesManager(),并在onCreate()中调用restoreModulesManager()..

问题是当我强制关闭(来自任务管理器)时,ObjectInputStream无法读取对象并且我得到“EOFException”..

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

以下是我将如何处理这个问题。这是一个只有标题字段的简单对象,但您可以对更复杂的对象使用相同的想法

public class MyObject implements Parcelable{

public String title;


public MyObject(){}


public MyObject(Parcel source){
    title = source.readString();

}


public void setTitle(String title){
    this.title = title;
}

public String getTitle(){
    return this.title;
}

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

@Override
public void writeToParcel(Parcel dest, int flags){

    dest.writeString(title);
}

// Parcelable Creator

public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>(){
    @Override
    public MyObject createFromParcel(Parcel source){
        return new MyObject(source);

    }

    @Override
    public MyObject [] newArray(int size){
        return new MyObject[size];
    }   
}
}

然后在您的类中实例化对象

 // Add this in onSavedInstanceState(Bundle outState)

 outState.putParcelableArray("MyObjectArray",myObjects);

然后在OnCreate或您用来恢复UI的任何方法

 // Add this

 myObjects = (MyObject [])savedInstanceState.getParcelableArray("MyObjectArray");