【发布时间】:2017-11-11 16:52:24
【问题描述】:
我想在本地文件中存储布尔数组列表并在 onCreate() 中加载值。 我正在使用
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,我的代码加载值在 listview 位置,因此它调用错误,因为长度为 0 而 inxed 用于示例 2. 这里有什么方法可以将整数和布尔列表保存/加载到文件中,或者我必须在保存之前将布尔和整数转换为字符串? 感谢您的每一个回复。
【问题讨论】:
-
您可以将其保存在共享首选项中。检查这个:(stackoverflow.com/questions/27159926/…)
-
你的代码在模拟器上为我工作@Martin
-
为什么这被标记为重复?