【问题标题】:Boolean arraylist in ObjectOutputStream [duplicate]ObjectOutputStream 中的布尔数组列表 [重复]
【发布时间】: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. 这里有什么方法可以将整数和布尔列表保存/加载到文件中,或者我必须在保存之前将布尔和整数转换为字符串? 感谢您的每一个回复。

【问题讨论】:

标签: java android arraylist


【解决方案1】:

另一种方法是保存共享首选项

给你:

 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;
}

【讨论】:

  • 请注意:必须添加 compile 'com.google.code.gson:gson:2.8.2' 但它可以工作,谢谢
猜你喜欢
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 2020-03-22
  • 2017-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多