Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store and retrieve a class object in shared preference

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.

like image 322
androidGuy Avatar asked Mar 24 '11 11:03

androidGuy


People also ask

Can you store objects in shared preferences?

We can store fields of any Object to shared preference by serializing the object to String.

How do you save the object of the model class in preferences?

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.

What is the method used to store and retrieve data on the SharedPreferences?

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.

How do I store class objects in SharedPreferences in Flutter?

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.


1 Answers

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

Update1

The latest version of GSON can be downloaded from github.com/google/gson.

Update2

If you are using Gradle/Android Studio just put following in build.gradle dependencies section -

implementation 'com.google.code.gson:gson:2.6.2' 
like image 98
Parag Chauhan Avatar answered Sep 18 '22 04:09

Parag Chauhan