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 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 getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class 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);
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
to Type classType
will make this solution generalized. Modified function signature,
public static GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
For invoking,
getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
Happy Coding!