2017-11-11 224 views
0

我想在本地文件中存儲布爾arraylist並在onCreate()中加載值。 我使用ObjectOutputStream中的布爾arraylist

public void saveBoolean(String fileName, ArrayList<Boolean> list){ 
    File file = new File(getDir("data", MODE_PRIVATE), fileName); 
    ObjectOutputStream outputStream = null; 
    try { 
     outputStream = new ObjectOutputStream(new FileOutputStream(file)); 
    } catch (IOException e) { 
     // 
    } 
    try { 
     outputStream.writeObject(list); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    try { 
     outputStream.flush(); 
    } catch (IOException e) { 
     // 
    } 
    try { 
     outputStream.close(); 
    } catch (IOException e) { 
     // 
    } 
} 

private ArrayList<Boolean> getSavedBooleanList(String fileName) { 
    ArrayList<Boolean> savedArrayList = new ArrayList<>(); 

    try { 
     File file = new File(getDir("data", MODE_PRIVATE), fileName); 
     ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); 
     savedArrayList = (ArrayList<Boolean>) ois.readObject(); 
     ois.close(); 
    } catch (IOException | ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 

    return savedArrayList; 
} 

但它調用NullPointerExcpetion時試圖初始化自定義視圖列表視圖。我也保存和加載字符串和整數列表像這樣,字符串列表被加載,但整數和布爾列表未被初始化,所以長度爲0,我的代碼加載值在列表視圖位置,所以它調用錯誤,因爲長度爲0,而inxed是爲示例2.是否有任何方法來保存/加載整數和布爾列表文件或我必須在保存前將布爾值和整數轉換爲字符串? 感謝您的回覆。

+0

你可以將其保存在共享偏好。檢查此:(https://stackoverflow.com/questions/27159926/how-to-add-a-boolean-array-in-shared-preferences-in-android) –

+0

您的代碼正在模擬器上工作@Martin –

+0

爲什麼這個被標記爲重複? –

回答

0

替代你的方法共享偏好是節省

在這裏你去:

private void saveToSharedPreference(ArrayList<Boolean> arrayList) { 
    Gson gson = new Gson(); 
    SharedPreferences sharedPreferences = this.getSharedPreferences("Test", Context.MODE_PRIVATE); 
    sharedPreferences.edit().putString("ArrayList", gson.toJson(arrayList)).commit(); 
} 

private ArrayList<Boolean> getSharedPreference() { 
    Gson gson = new Gson(); 
    SharedPreferences sharedPreferences = this.getSharedPreferences("Test", Context.MODE_PRIVATE); 
    String booleanString = sharedPreferences.getString("ArrayList", null); 
    TypeToken<ArrayList<Boolean>> typeToken = new TypeToken<ArrayList<Boolean>>() { 
    }; 
    ArrayList<Boolean> booleen = gson.fromJson(booleanString, typeToken.getType()); 
    return booleen; 
} 
+0

只是快速注意:編譯'com.google.code.gson:gson:2.8.2'必須被添加,但它的工作原理,謝謝 –