We 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);
Try this best way :
PreferenceConnector.java
Write the Value :
And Get value using :
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.
Then In Shared Preferences Class Do something like,
and then create a method for getPreferences
Then Just call the First method when you get response and second when you need to get data from share preferences like
that's all.
Hope it will help you.
Happy Coding();
Store data in SharedPreference
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 :
Retrieve Object from Preference:
Note :
Remember to add
compile 'com.google.code.gson:gson:2.6.2'
todependencies
in your gradle.Example :
Update:
As @Sharp_Edge pointed out in comments, the above solution does not work with
List
.A slight modification to the signature of
getSavedObjectFromPreference()
- fromClass<GenericClass> classType
toType classType
will make this solution generalized. Modified function signature,For invoking,
Happy Coding!