Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you save/store objects in SharedPreferences on Android?

I 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); 
like image 787
Piraba Avatar asked Aug 22 '11 09:08

Piraba


People also ask

Can I store object in SharedPreferences?

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

How do I save something in 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 can I store objects in Android?

If you're not storing an over abundance of data you can use Gson to convert a Java object to a Json string and store the string in your app preferences. Gson has a toJson(obj) method and visa-vis. Getting data out of app preferences and into an object: String json = appSharedPrefs.

How do you save custom objects in SharedPreferences in flutter?

SharedPreferences: Save and Read 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

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

you can find latest version here

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); 
like image 180
Muhammad Aamir Ali Avatar answered Oct 08 '22 09:10

Muhammad Aamir Ali