2

I am new in Android. I want to save JSON Array in Shared Preferences.

Here is My Java Code:

while (managedCursor.moveToNext())
{
    JSONObject jsonObject = new JSONObject();
    try
    {
        jsonObject.put("number", number);
        jsonObject.put("type", type);
        jsonObject.put("fDate", fDate);
        jsonObject.put("duration", duration);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    jsonArray.put(jsonObject);
}
managedCursor.close();
Log.d("array", jsonArray.toString());
David Tonhofer
  • 14,559
  • 5
  • 55
  • 51
Olicity_Emi
  • 31
  • 1
  • 7

1 Answers1

3

Firstly, I'd use Gson for converting json to/from Java objects,then can use something like following to store in SharedPreferences.

public void storeMyData(MyPojo myPojo) {
    preferences.edit().putString(SOME_SHARED_PREF_KEY, gson.toJson(myPojo)).commit();
}

convert json to string and save to sharedpreference

preferences.edit().putString(SOME_SHARED_PREF_KEY,jsonobject.toString()).commit();

on reading from sharedPreference convert back to json by

String string = preferences.getString(SOME_SHARED_PREF_KEY, null);
JsonObject jsonObject = new JsonObject(string);
Binil
  • 454
  • 3
  • 11
John O'Reilly
  • 10,000
  • 4
  • 41
  • 63