Monday, 1 July 2013

Store and Retrieve a class object in SharedPreference in Android



Store and Retrieve a class object in SharedPreference in Android


We can do this using gson.jar
Download this jar here
SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);
For save
        Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(MyObject);
        prefsEditor.putString("MyObject", json);
        prefsEditor.commit();
For get
    Gson gson = new Gson();
    String json = mPrefs.getString("MyObject", "");
    MyObject obj = gson.fromJson(json, MyObject.class);
 Download sourcecode

No comments:

Post a Comment