Search code examples
androidjsonandroid-studiobuttonclick

How to write in json file with Android


Hello ! I want to change the values ​​in my json file called "etatButton.json" but I do not know how.

[
{
    "bouton1":"on",
    "bouton2":"on",
    "bouton3":"on",
    "bouton4":"off",
    "bouton5":"on",
    "bouton6":"on",
    "bouton7":"on",
    "bouton8":"on",
    "bouton9":"off",
    "bouton10":"off"
}
]

For example I want to change the value of "bouton1" from "on" to "off" after onClick event like this one :

public void writeJson(View view) {
    // Write smth in json file
}

Thank you !


Solution

  • This code can get you started....

    try {
        JSONArray json = new JSONArray();
        JSONObject jsonobject =  new JSONObject();
        jsonobject.put("k1", "v1");
        jsonobject.put("k2", "v2");
        json.put(jsonobject);
        System.out.println(json);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    OUTPUT:

    [{"k1":"v1","k2":"v2"}]

    If you want to be able to change v1 or v2, just use variables