首页 > 解决方案 > 放置新对象后 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;
                }

标签: javaandroidarraysjsonsave

解决方案


也许在 file.flush(); 之后 你需要添加 file.close();


推荐阅读