java - 放置新对象后 JSON 文件未更新
问题描述
我有 json 文件,必须在开关按钮关闭或打开后更新。但是文件不保存新的给定对象。请检查我的代码,它有什么问题。为什么新的给定属性没有更新或保存。
这是我的 json 文件数据
{
"setting": [{
"message_switch_state": "true",
"voice_input_switch_state": "true"
}]
}
和我的代码
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@
Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("setting");
for (int i = 0; i < userArray.length(); i++) {
JSONObject object = userArray.getJSONObject(i);
object.remove("message_switch_state");
object.put("message_switch_state", "true");
try (FileWriter file = new FileWriter("states.json")) {
file.write(object.toString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
String state = object.getString("message_switch_state");
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets()
.open("states.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
解决方案
也许在 file.flush(); 之后 你需要添加 file.close();
推荐阅读
- ruby-on-rails - 在 docker-compose 中使用带有 pry 的键箭头时遇到问题
- matplotlib - 可以使用 Altair 的选择机制注册回调以交互更改 pandas 数据吗?
- python - tkinter 确认弹出和回调弹出
- ios - AVCaptureVideoPreviewLayer 转换捕获设备坐标不正确
- mysql - 触发更新产品数量
- python - 为什么 set_union = set_union.remove(i) 给出错误?
- python - Python Dataframe 重新采样列表数据
- reactjs - 无法使用 fetchCallback 对未安装的组件执行 React 状态更新
- google-apps-script - Google 表单提交按钮的 onClick 事件
- powershell - 当用户未登录时,修改 Word 文件的 PowerShell 脚本不适用于任务计划程序