3

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.

Onik
  • 19,396
  • 14
  • 68
  • 91
redrom
  • 11,502
  • 31
  • 157
  • 264

2 Answers2

8

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);
Salem
  • 12,808
  • 4
  • 34
  • 54
3

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()

Rogue
  • 751
  • 1
  • 17
  • 36
  • Yes, im converting created JSON into string before save using jsonData.toString(). Question is about creating JSON structure. not about purpose of saving JSON string in shared prefs. – redrom May 18 '14 at 06:29
  • I don't get it, sorry, you want to edit your JSON object and edit the value in sharedPreferences ? – Rogue May 18 '14 at 12:00