Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - how to add JSON object to sharedPreferences?

Tags:

json

android

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.

like image 867
redrom Avatar asked Dec 18 '25 04:12

redrom


2 Answers

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);
like image 72
Salem Avatar answered Dec 20 '25 17:12

Salem


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

like image 38
Rogue Avatar answered Dec 20 '25 16:12

Rogue