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.
we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:
when we need to extract Object from Preference. Use the code as below
There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,
Using Gson Library:
Store:
Retrieve:
You can do it using
PowerPreference
library in 3 easy steps!https://github.com/AliEsaAssadi/Android-Power-Preference
1. Create Object
2. Write to shared preference
3. Getting the object
You could use GSON, using Gradle Build.gradle :
Then in your code, for example pairs of string/boolean with Kotlin :
Adding to SharedPrefs :
Now to retrieve data :
Do you need to retrieve the object even after the application shutting donw or just during it's running ?
You can store it into a database.
Or Simply create a custom Application class.
And then from every activities do :
Not really the best way but it works.