I would like to append data into existing JSON object and save data as string into shared preferences with following structure.
"results":[
{
"lat":"value",
"lon":"value"
},
{
"lat":"value",
"lon":"value"
}
]
How can i do it right?
I tried something like this, but without luck.
// get stored JSON object with saved positions
String jsonDataString = this.getSharedPreferencesStringValue(ctx, "positions", "last_positions");
if (jsonDataString != null) {
Log.i(AppHelper.APP_LOG_NAMESPACE, "JSON DATA " + jsonDataString);
JSONObject jsonData = new JSONObject(jsonDataString);
jsonData.put("lat", lat.toString());
jsonData.put("lon", lon.toString());
jsonData.put("city", city);
jsonData.put("street", street);
jsonData.put("date", appHelper.getActualDateTime());
jsonData.put("time", appHelper.getActualDateTime());
this.setSharedPreferencesStringValue(ctx, "positions", "last_positions", jsonData.toString());
} else {
this.setSharedPreferencesStringValue(ctx, "positions", "last_positions","{}");
}
Thanks for any advice.
I think the easier way to achieve that would be using Gson.
If you are using gradle you can add it to your dependencies
compile 'com.google.code.gson:gson:2.2.4'
To use it you need to define classes to the objects you need to load. In your case it would be something like this:
// file MyObject.java
public class MyObject {
List<Coord> results = new ArrayList<Coord>();
public static class Coord {
public double lat;
public double lon;
}
Then just use it to go to/from Json whenever you need:
String jsonDataString = this.getSharedPreferencesStringValue(ctx, "positions", "last_positions");
Gson gson = new Gson();
MyObject obj = gson.fromJson(jsonDataString, MyObject.class);
// Noew obj contains your JSON data, so you can manipulate it at your will.
Coord newCoord = new Coord();
newCoord.lat = 34.66;
newCoord.lon = -4.567;
obj.results.add(newCoord);
String newJsonString = gson.toJson(obj);
SharedPreferences can only store basic type, such as String, integer, long, ... so you can't use it to store objects. However, you can store the Json String, using sharedPreferences.putString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With