In Android can we store an object of a class in shared preference and retrieve the object later?
If it is possible how to do it? If it is not possible what are the other possibilities of doing it?
I know that serialization is one option, but I am looking for possibilities using shared preference.
Yes we can do this using Gson
Download Working code from GitHub
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
For save
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
For get
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
The latest version of GSON can be downloaded from github.com/google/gson.
If you are using Gradle/Android Studio just put following in build.gradle
dependencies section -
implementation 'com.google.code.gson:gson:2.6.2'