Piraba Piraba - 7 months ago 31
Android Question

How Android SharedPreferences save/store object

My question is after login i want to save/store user object and executive Object. How we can implement this kind of scenario? because of I need to get the user object everywhere.This user contain many fields.I can't put in the

SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);

like this.

Please help me

thanks in advance


You can use gson.jar to store class objects into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list

Or add GSON dependency in Gradle file

compile 'com.google.code.gson:gson:2.5'


//Creating a shared preference
SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

To Save

     Editor prefsEditor = mPrefs.edit();
     Gson gson = new Gson();
     String json = gson.toJson(MyObject);
     prefsEditor.putString("MyObject", json);

To Retreive

    Gson gson = new Gson();
    String json = mPrefs.getString("MyObject", "");
    MyObject obj = gson.fromJson(json, MyObject.class);