I am working on an android application using a json file in order to store data used by the application. I have a Json file in the asset folder, including one object "plants". In the Dashboard.java file, I would like to add an object to the json file. I tried this by using the put() function, but I doesnt seem to write in the actual file. Dashboard.java :
String name = intent.getStringExtra(AddAPlant.EXTRA_TEXT1); String description = intent.getStringExtra(AddAPlant.EXTRA_TEXT2); String url = intent.getStringExtra(AddAPlant.EXTRA_TEXT3); JSONObject jsonObj= new JSONObject(); try { jsonObj.put("name", name); jsonObj.put("description", description); jsonObj.put("cameralink", url); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } plantArray = new JSONArray(); plantArray.put(jsonObj); Json file located in asset folder :
{ "plants": [ { "name": "Pepper", "decription": "This is a big plant", "CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png" }, { "name": "Tomatoe", "decription": "This is a big plant", "CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png" }, { "name": "Small Tomato", "decription": "It needs a lot of water", "CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png" } ] } Desired output :
{ "plants": [ { "name": "Pepper", "decription": "This is a big plant", "CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png" }, { "name": "Tomatoe", "decription": "This is a big plant", "CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png" }, { "name": "Small Tomato", "decription": "It needs a lot of water", "CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png" }, { "name": name, "decription": description, "CameraLink": url ] }
plantArrayby parsing its content from the json file. You can find instructions on how do it in the answers to this question: How to parse JSON array from file?