295

I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?

I can't store it like this:

SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Piraba
  • 6,974
  • 17
  • 85
  • 135

24 Answers24

706

You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson

Or add the GSON dependency in your Gradle file:

implementation 'com.google.code.gson:gson:2.8.8'

you can find latest version here

Creating a shared preference:

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

To save:

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.

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

To retrieve:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
Muhamed El-Banna
  • 593
  • 7
  • 21
Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57
  • 10
    Thanks friend! But you are incorrect in the Save part (line 3), the correct code is: String json = gson.toJson(myObject); – cesarferreira Sep 16 '13 at 22:24
  • Do you need all 3 jars? There are 3 of them in that link. . . – coolcool1994 Jul 13 '14 at 06:13
  • In Retrieve part, why are you creating new Gson gson, when you don't use it? – coolcool1994 Jul 13 '14 at 07:14
  • 3
    The correct URL for downloading the jar is: http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.3%7Cjar – Shajeel Afzal Oct 11 '14 at 04:04
  • duplicate of this answer: http://stackoverflow.com/questions/5418160/store-and-retrieve-a-class-object-in-shared-preference ... – Dolma Sep 17 '15 at 14:15
  • 3
    This has a problem with circular reference that leads to StackOverFlowException xD Read more here http://stackoverflow.com/questions/10209959/gson-tojson-throws-stackoverflowerror – phuwin Jul 29 '16 at 13:41
  • Why not just serialise the object and save it as String? Is Gson a better solution? – rozina Dec 22 '16 at 09:37
  • 1
    @rozina yes Gson is better. First of all to use serialize, the object and every object inside it needs to implement the serialize interface. This is not needed for gson. gson also works great when your object is a list of objects. – Neville Nazerane Jan 19 '17 at 07:26
  • This helped alot. – krisDrOid Jun 02 '17 at 00:18
  • Gson version as of December 12, 2017 --> `compile 'com.google.code.gson:gson:2.8.2'` – adadion Dec 12 '17 at 09:13
  • Does this way work for nested java objects too (along with nested objects containing lists of basic data and list of other objects) ? – Natesh bhat Jul 02 '18 at 03:07
  • SharedPreferences are backed by XML files. JSON quote (") is escape character in XML, which is getting replaced by `"`. This means that size and read/write time increase dramatically. It's better to save JSON in a separate file in internal storage. – Miha_x64 Jul 11 '18 at 20:32
  • 1
    In my case I needed to use "getSharedPreferences" instead of "getPreferences". – Αntonis Papadakis Jun 30 '20 at 07:33
  • Object Retrieving is giving Null – Emon Hossain Munna Dec 05 '20 at 05:32
47

To add to @MuhammadAamirALi's answer, you can use Gson to save and retrieve a list of objects

Save List of user-defined objects to SharedPreferences

public static final String KEY_CONNECTIONS = "KEY_CONNECTIONS";
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();

User entity = new User();
// ... set entity fields

List<Connection> connections = entity.getConnections();
// convert java object to JSON format,
// and returned as JSON formatted string
String connectionsJSONString = new Gson().toJson(connections);
editor.putString(KEY_CONNECTIONS, connectionsJSONString);
editor.commit();

Get List of user-defined objects from SharedPreferences

String connectionsJSONString = getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS, null);
Type type = new TypeToken < List < Connection >> () {}.getType();
List < Connection > connections = new Gson().fromJson(connectionsJSONString, type);
Etienne Lawlor
  • 6,817
  • 18
  • 77
  • 89
20

I know this thread is bit old. But I'm going to post this anyway hoping it might help someone. We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference.

Save Object to Preference :

public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
    SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
    final Gson gson = new Gson();
    String serializedObject = gson.toJson(object);
    sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
    sharedPreferencesEditor.apply();
}

Retrieve Object from Preference:

public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
    if (sharedPreferences.contains(preferenceKey)) {
        final Gson gson = new Gson();
        return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
    }
    return null;
}

Note :

Remember to add compile 'com.google.code.gson:gson:2.6.2' to dependencies in your gradle.

Example :

//assume SampleClass exists
SampleClass mObject = new SampleObject();

//to store an object
saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);

//to retrive object stored in preference
mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);

Update:

As @Sharp_Edge pointed out in comments, the above solution does not work with List.

A slight modification to the signature of getSavedObjectFromPreference() - from Class<GenericClass> classType to Type classType will make this solution generalized. Modified function signature,

public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)

For invoking,

getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)

Happy Coding!

mrtpk
  • 1,398
  • 4
  • 18
  • 38
  • 1
    this was really helpful thanks. For anyone here that cares to comment...should I put the call to saveObjectToSharedPreference in onSaveInstanceState? I have it in onSaveInstanceState now but , given my app is collecting real-time data every 10 seconds, I get a hiccup every once in a while and the object I am saving with saveObjectToSharedPreference loses some readings. All thoughts are welcome. – Frank Zappa Dec 05 '16 at 03:10
  • hey @FrankZappa, forgive me not completely understanding your problem but here you go, try using `commit` instead of `apply`. It might help you. – mrtpk Dec 05 '16 at 06:04
  • thanks. Let me try to explain. My Android app collects data in real-time approximately every 10 seconds. This data collection uses no objects, just global variables and logic. Next the data is then summarized and stored in a Java object. I use your method above to store and retrieve my Java object in/via SharedPreferences because a) to my knowledge I cannot store objects in onSavedInstanceState and b) when the screen rotates my object gets destroyed and recreated. Therefore, I am using your SharedPrefs approach so when the screen is rotated my object does not lose it's values. (cont..) – Frank Zappa Dec 06 '16 at 06:36
  • 1
    I placed your saveObjectToSharedPreferences routine in onSaveInstanceState. I placed your getSavedObjectFromPreference routine in onRestoreInstanceState. However, I tested and still got one set of missed object updates due to screen rotation. Therefore, should I move the call to saveObjectToSharedPreferences closer to my actual logic? Lastly what method does commit and apply pertain to? – Frank Zappa Dec 06 '16 at 06:41
  • Hello, Sorry for the late reply. I think you should call `saveObjectToSharedPreferences()` in `onStop()` and `getSavedObjectFromPreference()` in `onStart()` or `onCreate()`. These are called when orientation is changed. You need to be careful while starting and switching the activity. Other than that, it will be fine. `apply()` and `commit()` do the same thing in Asynchronous and synchronous way respectively. `commit()` returns `true` if the data is successfully stored. Another way of storing data is using data fragment. You should check that. – mrtpk Dec 07 '16 at 15:22
  • apologies for all the questions but if I use your onSavedInstanceState to save my data, I then shut the application down completely (destroy, you can no longer see the app), and I then invoke onRestoreInstanceState when my app restarts, will my data be restored? In other words does a sharedpreferences save last beyond the life of the application? – Frank Zappa Dec 14 '16 at 01:08
  • All the shared preference save will last beyond the life of the application provided it is not crashed/ uninstalled. – mrtpk Dec 15 '16 at 07:01
  • 1
    @2943 You solution looks great, but if I have list for example `List` how should i do that ? `getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class)` is not accepting `List.class` :( – Sharp Edge Feb 08 '17 at 17:21
  • You are right about that. The solution doesn't store a list to shared preference. I should modify the solution. – mrtpk Feb 09 '17 at 16:17
  • Please change `Class classType` to `Type classType` in `getSavedObjectFromPreference()` and it will solve the issue. Eg: for invoking,`getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)` – mrtpk Feb 09 '17 at 16:47
6

Better is to Make a global Constants class to save key or variables to fetch or save data.

To save data call this method to save data from every where.

public static void saveData(Context con, String variable, String data)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    prefs.edit().putString(variable, data).commit();
}

Use it to get data.

public static String getData(Context con, String variable, String defaultValue)
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
    String data = prefs.getString(variable, defaultValue);
    return data;
}

and a method something like this will do the trick

public static User getUserInfo(Context con)
{
    String id =  getData(con, Constants.USER_ID, null);
    String name =  getData(con, Constants.USER_NAME, null);
    if(id != null && name != null)
    {
            User user = new User(); //Hope you will have a user Object.
            user.setId(id);
            user.setName(name);
            //Here set other credentials.
            return user;
    }
    else
    return null;
}
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
  • In order to get the data back, what do I pass as the 'variable' and 'defaultValue'? – Alex Apr 02 '15 at 06:44
  • Never ever create a Constants class. It makes your code highly coupled and scattered at the same time. – Miha_x64 Jul 11 '18 at 20:35
5

Try this best way :

PreferenceConnector.java

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PreferenceConnector {
    public static final String PREF_NAME = "ENUMERATOR_PREFERENCES";
    public static final String PREF_NAME_REMEMBER = "ENUMERATOR_REMEMBER";
    public static final int MODE = Context.MODE_PRIVATE;


    public static final String name = "name";


    public static void writeBoolean(Context context, String key, boolean value) {
        getEditor(context).putBoolean(key, value).commit();
    }

    public static boolean readBoolean(Context context, String key,
            boolean defValue) {
        return getPreferences(context).getBoolean(key, defValue);
    }

    public static void writeInteger(Context context, String key, int value) {
        getEditor(context).putInt(key, value).commit();

    }

    public static int readInteger(Context context, String key, int defValue) {
        return getPreferences(context).getInt(key, defValue);
    }

    public static void writeString(Context context, String key, String value) {
        getEditor(context).putString(key, value).commit();

    }

    public static String readString(Context context, String key, String defValue) {
        return getPreferences(context).getString(key, defValue);
    }

    public static void writeLong(Context context, String key, long value) {
        getEditor(context).putLong(key, value).commit();
    }

    public static long readLong(Context context, String key, long defValue) {
        return getPreferences(context).getLong(key, defValue);
    }

    public static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, MODE);
    }

    public static Editor getEditor(Context context) {
        return getPreferences(context).edit();
    }

}

Write the Value :

PreferenceConnector.writeString(this, PreferenceConnector.name,"Girish");

And Get value using :

String name= PreferenceConnector.readString(this, PreferenceConnector.name, "");
Girish Patel
  • 1,270
  • 4
  • 16
  • 30
  • 2
    What does this have to do with saving an object in SharedPreferences on Android? – IgorGanapolsky Jun 16 '16 at 15:22
  • More info about working with Sharedpreferences can be found at http://stackoverflow.com/a/2614771/1815624 note you might want to use`return PreferenceManager.getDefaultSharedPreferences(context);` instead of `return context.getSharedPreferences(PREF_NAME, MODE);` – CrandellWS Dec 21 '16 at 09:33
5

You can use the following code to store class objects and to retrieve any object from shared preferences.

Add the following dependency to the app gradle

dependencies {
 implementation 'com.google.code.gson:gson:2.8.6'
 //Other dependencies of our project
} 

Add the following code in your shared pref file.

 /**
 * Saves object into the Preferences.
 *
 * @param `object` Object of model class (of type [T]) to save
 * @param key Key with which Shared preferences to
 **/
fun <T> put(`object`: T, key: String) {
    //Convert object to JSON String.
    val jsonString = GsonBuilder().create().toJson(`object`)
    //Save that String in SharedPreferences
    preferences.edit().putString(key, jsonString).apply()
}

/**
 * Used to retrieve object from the Preferences.
 *
 * @param key Shared Preference key with which object was saved.
 **/
inline fun <reified T> get(key: String): T? {
    //We read JSON String which was saved.
    val value = preferences.getString(key, null)
    //JSON String was found which means object can be read.
    //We convert this JSON String to model object. Parameter "c" (of
    //type Class < T >" is used to cast.
    return GsonBuilder().create().fromJson(value, T::class.java)
}
}
Sahil Bansal
  • 609
  • 8
  • 6
4

Using Delegation Kotlin we can easily put and get data from shared preferences.

    inline fun <reified T> Context.sharedPrefs(key: String) = object : ReadWriteProperty<Any?, T> {

        val sharedPrefs by lazy { this@sharedPrefs.getSharedPreferences("APP_DATA", Context.MODE_PRIVATE) }
        val gson by lazy { Gson() }
        var newData: T = (T::class.java).newInstance()

        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return getPrefs()
        }

        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
            this.newData = value
            putPrefs(newData)
        }

        fun putPrefs(value: T?) {
            sharedPrefs.edit {
                when (value) {
                    is Int -> putInt(key, value)
                    is Boolean -> putBoolean(key, value)
                    is String -> putString(key, value)
                    is Long -> putLong(key, value)
                    is Float -> putFloat(key, value)
                    is Parcelable -> putString(key, gson.toJson(value))
                    else          -> throw Throwable("no such type exist to put data")
                }
            }
        }

        fun getPrefs(): T {
            return when (newData) {
                       is Int -> sharedPrefs.getInt(key, 0) as T
                       is Boolean -> sharedPrefs.getBoolean(key, false) as T
                       is String -> sharedPrefs.getString(key, "") as T ?: "" as T
                       is Long -> sharedPrefs.getLong(key, 0L) as T
                       is Float -> sharedPrefs.getFloat(key, 0.0f) as T
                       is Parcelable -> gson.fromJson(sharedPrefs.getString(key, "") ?: "", T::class.java)
                       else          -> throw Throwable("no such type exist to put data")
                   } ?: newData
        }

    }

    //use this delegation in activity and fragment in following way
        var ourData by sharedPrefs<String>("otherDatas")
Axiumin_
  • 2,107
  • 2
  • 15
  • 24
3

You can save object in preferences without using any library, first of all your object class must implement Serializable:

public class callModel implements Serializable {

private long pointTime;
private boolean callisConnected;

public callModel(boolean callisConnected,  long pointTime) {
    this.callisConnected = callisConnected;
    this.pointTime = pointTime;
}
public boolean isCallisConnected() {
    return callisConnected;
}
public long getPointTime() {
    return pointTime;
}

}

Then you can easily use these two method to convert object to string and string to object:

 public static <T extends Serializable> T stringToObjectS(String string) {
    byte[] bytes = Base64.decode(string, 0);
    T object = null;
    try {
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        object = (T) objectInputStream.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return object;
}

 public static String objectToString(Parcelable object) {
    String encoded = null;
    try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        encoded = new String(Base64.encodeToString(byteArrayOutputStream.toByteArray(), 0));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return encoded;
}

To save:

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
prefsEditor.putString("MyObject", objectToString(callModelObject));
prefsEditor.commit();

To read

String value= mPrefs.getString("MyObject", "");
MyObject obj = stringToObjectS(value);
farhad.kargaran
  • 2,233
  • 1
  • 24
  • 30
3

I had trouble using the accepted answer to access Shared Preference data across activities. In these steps, you give getSharedPreferences a name to access it.

Add the following dependency in the build.gradel (Module: app) file under Gradle Scripts:

implementation 'com.google.code.gson:gson:2.8.5'

To Save:

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.

SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);

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

To Retrieve in a Different Activity:

SharedPreferences mPrefs = getSharedPreferences("Name", Context.MODE_PRIVATE);

Gson gson = new Gson();
String json = mPrefs.getString("Key", "");
MyObject obj = gson.fromJson(json, MyObject.class);
Ben
  • 3,346
  • 6
  • 32
  • 51
3

You haven't stated what you do with the prefsEditor object after this, but in order to persist the preference data, you also need to use:

prefsEditor.commit();
RivieraKid
  • 5,923
  • 4
  • 38
  • 47
2

See here, this can help you:

public static boolean setObject(Context context, Object o) {
        Field[] fields = o.getClass().getFields();
        SharedPreferences sp = context.getSharedPreferences(o.getClass()
                .getName(), Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        for (int i = 0; i < fields.length; i++) {
            Class<?> type = fields[i].getType();
            if (isSingle(type)) {
                try {
                    final String name = fields[i].getName();
                    if (type == Character.TYPE || type.equals(String.class)) {
                        Object value = fields[i].get(o);
                        if (null != value)
                            editor.putString(name, value.toString());
                    } else if (type.equals(int.class)
                            || type.equals(Short.class))
                        editor.putInt(name, fields[i].getInt(o));
                    else if (type.equals(double.class))
                        editor.putFloat(name, (float) fields[i].getDouble(o));
                    else if (type.equals(float.class))
                        editor.putFloat(name, fields[i].getFloat(o));
                    else if (type.equals(long.class))
                        editor.putLong(name, fields[i].getLong(o));
                    else if (type.equals(Boolean.class))
                        editor.putBoolean(name, fields[i].getBoolean(o));

                } catch (IllegalAccessException e) {
                    LogUtils.e(TAG, e);
                } catch (IllegalArgumentException e) {
                    LogUtils.e(TAG, e);
                }
            } else {
                // FIXME 是对象则不写入
            }
        }

        return editor.commit();
    }

https://github.com/AltasT/PreferenceVObjectFile/blob/master/PreferenceVObjectFile/src/com/altas/lib/PreferenceUtils.java

Şafak Gezer
  • 3,928
  • 3
  • 47
  • 49
Altas
  • 21
  • 1
  • 2
    Could you explain the code a little more as this currently represents just "a bunch of code". – Werner Sep 27 '14 at 13:08
2
// SharedPrefHelper is a class contains the get and save sharedPrefernce data
public class SharedPrefHelper {

    // save data in sharedPrefences
    public static void setSharedOBJECT(Context context, String key, 
                                           Object value) {

        SharedPreferences sharedPreferences =  context.getSharedPreferences(
                context.getPackageName(), Context.MODE_PRIVATE);

        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(value);
        prefsEditor.putString(key, json);
        prefsEditor.apply();
    }

    // get data from sharedPrefences 
    public static Object getSharedOBJECT(Context context, String key) {

         SharedPreferences sharedPreferences = context.getSharedPreferences(
                           context.getPackageName(), Context.MODE_PRIVATE);

        Gson gson = new Gson();
        String json = sharedPreferences.getString(key, "");
        Object obj = gson.fromJson(json, Object.class);
        User objData = new Gson().fromJson(obj.toString(), User.class);
        return objData;
    }
}
// save data in your activity

User user = new User("Hussein","h@h.com","3107310890983");        
SharedPrefHelper.setSharedOBJECT(this,"your_key",user);        
User data = (User) SharedPrefHelper.getSharedOBJECT(this,"your_key");

Toast.makeText(this,data.getName()+"\n"+data.getEmail()+"\n"+data.getPhone(),Toast.LENGTH_LONG).show();
// User is the class you want to save its objects

public class User {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    private String name,email,phone;
    public User(String name,String email,String phone){
          this.name=name;
          this.email=email;
          this.phone=phone;
    }
}
// put this in gradle

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

hope this helps you :)

nunya07
  • 65
  • 1
  • 8
HusseinKamal
  • 121
  • 1
  • 5
2

So many good answers, her are my 2 cents

i prefer to use inline function and old style of put and get value

object PreferenceHelper {

    private const val PREFERENCES_KEY = "MyLocalPreference"

    private fun getPreference(context: Context): SharedPreferences {
        return context.getSharedPreferences(
            PREFERENCES_KEY,
            Context.MODE_PRIVATE
        )
    }

    fun setBoolean(appContext: Context, key: String?, value: Boolean?) =
        getPreference(appContext).edit().putBoolean(key, value!!).apply()

    fun setInteger(appContext: Context, key: String?, value: Int) =
        getPreference(appContext).edit().putInt(key, value).apply()

    fun setFloat(appContext: Context, key: String?, value: Float) =
        getPreference(appContext).edit().putFloat(key, value).apply()

    fun setString(appContext: Context, key: String?, value: String?) =
        getPreference(appContext).edit().putString(key, value).apply()

    // To retrieve values from shared preferences:
    fun getBoolean(appContext: Context, key: String?, defaultValue: Boolean?): Boolean =
        getPreference(appContext).getBoolean(key, defaultValue!!)

    fun getInteger(appContext: Context, key: String?, defaultValue: Int): Int =
        getPreference(appContext)
            .getInt(key, defaultValue)

    fun getString(appContext: Context, key: String?, defaultValue: String?): String? =
        getPreference(appContext)
            .getString(key, defaultValue)


}

Usage

PreferenceHelper.setString(context,"CUSTOMER_NAME", "HITESH")

Toast.makeText(context, "Hello " + PreferenceHelper.getString(context,"CUSTOMER_NAME", "User"), Toast.LENGTH_LONG).show()
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
1

If you want to store the whole Object that you get in response, It can achieve by doing something like,

First Create a method that converts your JSON into a string in your util class as below.

 public static <T> T fromJson(String jsonString, Class<T> theClass) {
    return new Gson().fromJson(jsonString, theClass);
}

Then In Shared Preferences Class Do something like,

 public void storeLoginResponse(yourResponseClass objName) {

    String loginJSON = UtilClass.toJson(customer);
    if (!TextUtils.isEmpty(customerJSON)) {
        editor.putString(AppConst.PREF_CUSTOMER, customerJSON);
        editor.commit();
    }
}

and then create a method for getPreferences

public Customer getCustomerDetails() {
    String customerDetail = pref.getString(AppConst.PREF_CUSTOMER, null);
    if (!TextUtils.isEmpty(customerDetail)) {
        return GSONConverter.fromJson(customerDetail, Customer.class);
    } else {
        return new Customer();
    }
}

Then Just call the First method when you get response and second when you need to get data from share preferences like

String token = SharedPrefHelper.get().getCustomerDetails().getAccessToken();

that's all.

Hope it will help you.

Happy Coding();

Naresh
  • 301
  • 4
  • 9
1

Step 1: Copy paste these two functions in your java file.

 public void setDefaults(String key, String value, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }


    public static String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }

Step 2: to save use:

 setDefaults("key","value",this);

to retrieve use:

String retrieve= getDefaults("key",this);

You can set different shared preferences by using different key names like:

setDefaults("key1","xyz",this);

setDefaults("key2","abc",this);

setDefaults("key3","pqr",this);
d219
  • 2,707
  • 5
  • 31
  • 36
Viraj Singh
  • 1,951
  • 1
  • 17
  • 27
1

there are two file solved your all problem about sharedpreferences

1)AppPersistence.java

    public class AppPersistence {
    public enum keys {
        USER_NAME, USER_ID, USER_NUMBER, USER_EMAIL, USER_ADDRESS, CITY, USER_IMAGE,
        DOB, MRG_Anniversary, COMPANY, USER_TYPE, support_phone
    }

    private static AppPersistence mAppPersistance;
    private SharedPreferences sharedPreferences;

    public static AppPersistence start(Context context) {
        if (mAppPersistance == null) {
            mAppPersistance = new AppPersistence(context);
        }
        return mAppPersistance;
    }

    private AppPersistence(Context context) {
        sharedPreferences = context.getSharedPreferences(context.getString(R.string.prefrence_file_name),
                Context.MODE_PRIVATE);
    }

    public Object get(Enum key) {
        Map<String, ?> all = sharedPreferences.getAll();
        return all.get(key.toString());
    }

    void save(Enum key, Object val) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (val instanceof Integer) {
            editor.putInt(key.toString(), (Integer) val);
        } else if (val instanceof String) {
            editor.putString(key.toString(), String.valueOf(val));
        } else if (val instanceof Float) {
            editor.putFloat(key.toString(), (Float) val);
        } else if (val instanceof Long) {
            editor.putLong(key.toString(), (Long) val);
        } else if (val instanceof Boolean) {
            editor.putBoolean(key.toString(), (Boolean) val);
        }
        editor.apply();
    }

    void remove(Enum key) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key.toString());
        editor.apply();
    }

    public void removeAll() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}

2)AppPreference.java

public static void setPreference(Context context, Enum Name, String Value) {
        AppPersistence.start(context).save(Name, Value);
    }

    public static String getPreference(Context context, Enum Name) {
        return (String) AppPersistence.start(context).get(Name);
    }

    public static void removePreference(Context context, Enum Name) {
        AppPersistence.start(context).remove(Name);
    }
}

now you can save,remove or get like,

-save

AppPreference.setPreference(context, AppPersistence.keys.USER_ID, userID);

-remove

AppPreference.removePreference(context, AppPersistence.keys.USER_ID);

-get

 AppPreference.getPreference(context, AppPersistence.keys.USER_ID);
Gautam Surani
  • 1,136
  • 10
  • 21
  • Add the dependency in the app build.gradel file under Gradle Scripts: implementation 'com.google.code.gson:gson:2.8.5' Please update your answer. – H_H Jun 18 '21 at 05:05
1

My utils class for save list to SharedPreferences

public class SharedPrefApi {
    private SharedPreferences sharedPreferences;
    private Gson gson;

    public SharedPrefApi(Context context, Gson gson) {
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = gson;
    } 

    ...

    public <T> void putObject(String key, T value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, gson.toJson(value));
        editor.apply();
    }

    public <T> T getObject(String key, Class<T> clazz) {
        return gson.fromJson(getString(key, null), clazz);
    }
}

Using

// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);

// for retrieve
List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);

.
Full code of my utils // check using example in Activity code

Linh
  • 57,942
  • 23
  • 262
  • 279
1

Here's a take on using Kotlin Delegated Properties that I picked up from here, but expanded on and allows for a simple mechanism for getting/setting SharedPreference properties.

For String, Int, Long, Float or Boolean, it uses the standard SharePreference getter(s) and setter(s). However, for all other data classes, it uses GSON to serialize to a String, for the setter. Then deserializes to the data object, for the getter.

Similar to other solutions, this requires adding GSON as a dependency in your gradle file:

implementation 'com.google.code.gson:gson:2.8.6'

Here's an example of a simple data class that we would want to be able to save and store to SharedPreferences:

data class User(val first: String, val last: String)

Here is the one class that implements the property delegates:

object UserPreferenceProperty : PreferenceProperty<User>(
    key = "USER_OBJECT",
    defaultValue = User(first = "Jane", last = "Doe"),
    clazz = User::class.java)

object NullableUserPreferenceProperty : NullablePreferenceProperty<User?, User>(
    key = "NULLABLE_USER_OBJECT",
    defaultValue = null,
    clazz = User::class.java)

object FirstTimeUser : PreferenceProperty<Boolean>(
        key = "FIRST_TIME_USER",
        defaultValue = false,
        clazz = Boolean::class.java
)

sealed class PreferenceProperty<T : Any>(key: String,
                                         defaultValue: T,
                                         clazz: Class<T>) : NullablePreferenceProperty<T, T>(key, defaultValue, clazz)

@Suppress("UNCHECKED_CAST")
sealed class NullablePreferenceProperty<T : Any?, U : Any>(private val key: String,
                                                           private val defaultValue: T,
                                                           private val clazz: Class<U>) : ReadWriteProperty<Any, T> {

    override fun getValue(thisRef: Any, property: KProperty<*>): T = HandstandApplication.appContext().getPreferences()
            .run {
                when {
                    clazz.isAssignableFrom(String::class.java) -> getString(key, defaultValue as String?) as T
                    clazz.isAssignableFrom(Int::class.java) -> getInt(key, defaultValue as Int) as T
                    clazz.isAssignableFrom(Long::class.java) -> getLong(key, defaultValue as Long) as T
                    clazz.isAssignableFrom(Float::class.java) -> getFloat(key, defaultValue as Float) as T
                    clazz.isAssignableFrom(Boolean::class.java) -> getBoolean(key, defaultValue as Boolean) as T
                    else -> getObject(key, defaultValue, clazz)
                }
            }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = HandstandApplication.appContext().getPreferences()
            .edit()
            .apply {
                when {
                    clazz.isAssignableFrom(String::class.java) -> putString(key, value as String?) as T
                    clazz.isAssignableFrom(Int::class.java) -> putInt(key, value as Int) as T
                    clazz.isAssignableFrom(Long::class.java) -> putLong(key, value as Long) as T
                    clazz.isAssignableFrom(Float::class.java) -> putFloat(key, value as Float) as T
                    clazz.isAssignableFrom(Boolean::class.java) -> putBoolean(key, value as Boolean) as T
                    else -> putObject(key, value)
                }
            }
            .apply()

    private fun Context.getPreferences(): SharedPreferences = getSharedPreferences(APP_PREF_NAME, Context.MODE_PRIVATE)

    private fun <T, U> SharedPreferences.getObject(key: String, defValue: T, clazz: Class<U>): T =
            Gson().fromJson(getString(key, null), clazz) as T ?: defValue

    private fun <T> SharedPreferences.Editor.putObject(key: String, value: T) = putString(key, Gson().toJson(value))

    companion object {
        private const val APP_PREF_NAME = "APP_PREF"
    }
}

Note: you shouldn't need to update anything in the sealed class. The delegated properties are the Object/Singletons UserPreferenceProperty, NullableUserPreferenceProperty and FirstTimeUser.

To setup a new data object for saving/getting from SharedPreferences, it's now as easy as adding four lines:

object NewPreferenceProperty : PreferenceProperty<String>(
        key = "NEW_PROPERTY",
        defaultValue = "",
        clazz = String::class.java)

Finally, you can read/write values to SharedPreferences by just using the by keyword:

private var user: User by UserPreferenceProperty
private var nullableUser: User? by NullableUserPreferenceProperty
private var isFirstTimeUser: Boolean by 

Log.d("TAG", user) // outputs the `defaultValue` for User the first time
user = User(first = "John", last = "Doe") // saves this User to the Shared Preferences
Log.d("TAG", user) // outputs the newly retrieved User (John Doe) from Shared Preferences
Jason Grife
  • 1,197
  • 11
  • 14
1

To store ArrayList of Model in SharedPreferences

  1. Add this dependency

    implementation 'com.google.code.gson:gson:2.8.8'
    
  2. Then after you convert your Model Class into JSON using Gson.

    Gson gson = new Gson();
    String json = gson.toJson(chModelArrayList); //here chModelArrayList is a ArrayList<Model> of Model Class
    
  3. Then after you can add this string to SharedPreferences

    SharedPreferences preferences; //Create Object of SharedPreferences 
    SharedPreferences.Editor editor; //Create Object of SharedPreferences.Editor
    
    //initialize SharedPreferences
    preferences = activity.getPreferences(Context.MODE_PRIVATE);
    editor = preferences.edit();
    
    //Add-In SharedPreferences
    editor.putString(key, json);
    editor.commit();
    
  4. for your list from SharedPreferences

    String json = preferences.getString(key, defVal);
    
    Gson gson = new Gson();
    
    //Pass Your Model ArrayList in TypeToken
    Type type = new TypeToken<ArrayList<ChModel>>() {}.getType();
    
    //here you get your list
    ArrayList<ChModel> switchGroup1 = gson.fromJson(json, type); 
    
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
jcredking
  • 314
  • 1
  • 10
0

An other way to save and restore an object from android sharedpreferences without using the Json format

private static ExampleObject getObject(Context c,String db_name){
            SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            ExampleObject o = new ExampleObject();
            Field[] fields = o.getClass().getFields();
            try {
                for (Field field : fields) {
                    Class<?> type = field.getType();
                    try {
                        final String name = field.getName();
                        if (type == Character.TYPE || type.equals(String.class)) {
                            field.set(o,sharedPreferences.getString(name, ""));
                        } else if (type.equals(int.class) || type.equals(Short.class))
                            field.setInt(o,sharedPreferences.getInt(name, 0));
                        else if (type.equals(double.class))
                            field.setDouble(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(float.class))
                            field.setFloat(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(long.class))
                            field.setLong(o,sharedPreferences.getLong(name, 0));
                        else if (type.equals(Boolean.class))
                            field.setBoolean(o,sharedPreferences.getBoolean(name, false));
                        else if (type.equals(UUID.class))
                            field.set(
                                    o,
                                    UUID.fromString(
                                            sharedPreferences.getString(
                                                    name,
                                                    UUID.nameUUIDFromBytes("".getBytes()).toString()
                                            )
                                    )
                            );

                    } catch (IllegalAccessException e) {
                        Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                    } catch (IllegalArgumentException e) {
                        Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
            return o;
        }
        private static void setObject(Context context, Object o, String db_name) {
            Field[] fields = o.getClass().getFields();
            SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            for (Field field : fields) {
                Class<?> type = field.getType();
                try {
                    final String name = field.getName();
                    if (type == Character.TYPE || type.equals(String.class)) {
                        Object value = field.get(o);
                        if (value != null)
                            editor.putString(name, value.toString());
                    } else if (type.equals(int.class) || type.equals(Short.class))
                        editor.putInt(name, field.getInt(o));
                    else if (type.equals(double.class))
                        editor.putFloat(name, (float) field.getDouble(o));
                    else if (type.equals(float.class))
                        editor.putFloat(name, field.getFloat(o));
                    else if (type.equals(long.class))
                        editor.putLong(name, field.getLong(o));
                    else if (type.equals(Boolean.class))
                        editor.putBoolean(name, field.getBoolean(o));
                    else if (type.equals(UUID.class))
                        editor.putString(name, field.get(o).toString());

                } catch (IllegalAccessException e) {
                    Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                } catch (IllegalArgumentException e) {
                    Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                }
            }

            editor.apply();
        }
William Desportes
  • 1,412
  • 1
  • 22
  • 31
0

Store data in SharedPreference

SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
mprefs.edit().putString(AppConstant.USER_ID, resUserID).apply();
0

I've used jackson to store my objects (jackson).

Added jackson library to gradle:

api 'com.fasterxml.jackson.core:jackson-core:2.9.4'
api 'com.fasterxml.jackson.core:jackson-annotations:2.9.4'
api 'com.fasterxml.jackson.core:jackson-databind:2.9.4'

My test class:

public class Car {
    private String color;
    private String type;
    // standard getters setters
}

Java Object to JSON:

ObjectMapper objectMapper = new ObjectMapper();
String carAsString = objectMapper.writeValueAsString(car);

Store it in shared preferences:

preferences.edit().car().put(carAsString).apply();

Restore it from shared preferences:

ObjectMapper objectMapper = new ObjectMapper();
Car car = objectMapper.readValue(preferences.car().get(), Car.class);
Manuel Schmitzberger
  • 5,162
  • 3
  • 36
  • 45
0

If your Object is complex I'd suggest to Serialize/XML/JSON it and save those contents to the SD card. You can find additional info on how to save to external storage here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

trenpixster
  • 390
  • 1
  • 3
  • 12
0

So many great answers on this question, implementation of the answer by Muhammad Aamir Ali & Muhamed El-Banna in Kotlin using the generic approach.

To save

fun storeObjectInSharedPref(dataObject: Any, prefName: String): Boolean{
    val dataObjectInJson = Gson().toJson(dataObject)
    prefsEditor.putString(prefName, dataObjectInJson)
    return prefsEditor.commit()
}

To Retrieve

fun <T> retrieveStoredObject(prefName: String, baseClass: Class<T>): T?{
    val dataObject: String? = preferences.getString(prefName, "")
    return Gson().fromJson(dataObject, baseClass)
}

To learn about generics in Kotlin visit here

Paul Kunda
  • 49
  • 2