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 store fields of any Object to shared preference by serializing the object to String.
In Android, SharedPreferences class can save only these: We use the GSON library to convert the model class to JSON String and we save that JSON String into the SharedPreferences. We read back that JSON String and convert it back to the object when we want to read it.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
First, in order to use the SharedPreferences , we have to use Flutter's plugin for it. To do so, make sure dependencies in your pubspec. yaml file looks similar to this: To save something in SharedPreferences , we must provide a value that we want to save and a key that identifies it.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With