Wednesday 9 January 2019

How Android SharedPreferences save/store object



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);

Answer




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.5'


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);


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...