簡體   English   中英

將數據對象列表持久保存在android內部

[英]Saving list of data objects persistent internal in android

我有一堂課,有很多對象,例如

private class MyDataStuff{

    private String mostInterestingString;
    private int    veryImportantNumber
    //...you get the idea

    public MyDatastuff{
    //init stuff...
    }

    //some getter methods        

}

此外,我有一個類,可以將其命名為User ,其中包含MyDataStuff ,一些long,Strings等列表。我想將User對象存儲到內部存儲器中的文件中。 我用以下代碼嘗試了它:

//loading
try{
        FileInputStream fis = this.getApplicationContext().openFileInput("UserData.data");
        ObjectInputStream is = new ObjectInputStream(fis);
        User loadedUser = (User) is.readObject();
        is.close();
        fis.close();
        appUser = loadedUser;
    }catch (Exception e){
        Log.e("MainActivity", "Error: loading from the internal storage failed - \n" + e.toString());

}
//Saving
if(appUser == null){
    Log.e("MainActivity", "Create new User");
    appUser = new User();
    try{
        FileOutputStream fos = this.getApplicationContext().openFileOutput("UserData.data", Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(this);
        os.close();
        fos.close();
    }catch (Exception e){
        Log.e("MainActivity", "Error: Failed to save User into internal storage - \n" + e.toString());
    }
}

這導致一個java.io.NotSerializableException 我閱讀了Serializable-documentation並進行了測試,使類User實現Serializable,並刪除了除long和Strings之外的所有屬性。 它仍然導致此異常,這使我相信默認情況下字符串或long都不可序列化。

我需要將對象保存為當前狀態。 有什么更好的方法可以做我想做的事情,如果沒有,我該如何解決這個問題?

仔細查看您的序列化代碼。

//Saving
if(appUser == null){
    Log.e("MainActivity", "Create new User");
    appUser = new User();
    try{
        FileOutputStream fos = this.getApplicationContext()
                .openFileOutput("UserData.data", Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(this);
        ...

您正在創建一個新的User對象,但是您正在this序列化,我猜它是ActivityFragment 因此,您將收到NotSerializableException

StringLong序列化。 但是,如果最終的User實現將具有MyDataStuff的列表, MyDataStuff還必須標記其類Serializable

如果要存儲用戶對象,則需要編寫appUser對象,而不是“ this”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM