Reputation: 113
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
]
}
Upvotes: 1
Views: 1090
Reputation: 471
i do not think it is possible to write to /assets at run time check this answer
try using app specific files docs
To make changes to JSON. Read from file (String data) and initialize a JSONobject.
JSONObject obj = new JSONObject("string from your file")
JSONObject jsonObject = new JSONObject("data from file");
JSONArray jsonArray = jsonObject.getJSONArray("plants");
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", name);
jsonObj.put("description", description);
jsonObj.put("cameralink", url);
jsonArray = jsonArray.put(jsonObj);
jsonObject = jsonObject.put("plants", jsonArray);
//convert json object to string
String data = jsonObject.toString();
FileOutputStream fout = context.openFileOutput(filename, Context.MODE_PRIVATE);
fout.write(data.getBytes());
Upvotes: 1