2017-11-11 225 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'必须被添加,但它的工作原理,谢谢 –