How do you save/store objects in SharedPreferences on Android?
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);
How to save data object in sharedpreference from retrofit2. More information inside
You should convert it in JSON and store it as a String :
class SharedPreferenceManager(val context: Context) {
private val PREFS_NAME = "sharedpref"
val sharedPref: SharedPreferences =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun saveUSer(user: CurrentUser) {
sharedPref.edit().putString("user", Gson().toJson(user)).apply()
}
fun getUser(): CurrentUser? {
val data = sharedPref.getString("user", null)
if (data == null) {
return null
}
return Gson().fromJson(data, CurrentUser::class.java)
}
}
store and retrieve a class object in shared preference
Not possible.
You can only store, simple values in SharedPrefences SharePreferences.Editor
What particularly about the class do you need to save?
Android - save Object to SharedPreferences and get it anywhere in the app
Replace your existing User class with below
public class User implements Serializable
{
private static User userInstance = null; // the only instance of the class
private String userName; // userName = the short phone number
private User(){}
public static User getInstance()
{
if (userInstance == null)
{
userInstance = new User();
}
return userInstance;
}
public String getUserName()
{
return userName;
}
public void setUserName(String p_userName)
{
userName = p_userName;
}
@Override
public String toString()
{
return "User [userName=" + getUserName() + "]";
}
}
Initialize User Name
User m_user = User.getInstance();
m_user.setUserName(name);
Convert the object to a String
Gson gson = new Gson();
String stringUser = gson.toJson(m_user);
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);
How to save List Object to SharedPreferences?
It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:
private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
private static SharedPreferences.Editor editor = sharedPreferences.edit();
public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
set(key, json);
}
public static void set(String key, String value) {
editor.putString(key, value);
editor.commit();
}
Extra Shot from below comment by @StevenTB
To Retrive
public List<YourModel> getList(){
List<YourModel> arrayItems;
String serializedObject = sharedPreferences.getString(KEY_PREFS, null);
if (serializedObject != null) {
Gson gson = new Gson();
Type type = new TypeToken<List<YourModel>>(){}.getType();
arrayItems = gson.fromJson(serializedObject, type);
}
}
Store data as an object in shared preferences in flutter
You need to serialize it to JSON before saving and deserialize after reading
See https://flutter.io/docs/development/data-and-backend/json for details
Save Model class object in SharedPreferences
this one to save data
public void saveData(String key, MyModel object) {
save(key, new Gson().toJson(object));
}
this one to get data
public MyModel getData(String key) {
String data = get(key);
return new Gson().fromJson(data, MyModel.class);
}
How it works?
This save method converts your model object into a JSON string and then the string is saved into shared preferences and the same in get function. It gets data in the form of JSON string and then it converts it to your object and returns a value.
For save and get use your own functions
Save ArrayList to SharedPreferences
After API 11 the SharedPreferences Editor
accepts Sets
. You could convert your List into a HashSet
or something similar and store it like that. When you read it back, convert it into an ArrayList
, sort it if needed and you're good to go.
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
You can also serialize your ArrayList
and then save/read it to/from SharedPreferences
. Below is the solution:
EDIT:
Ok, below is the solution to save ArrayList
as a serialized object to SharedPreferences
and then read it from SharedPreferences.
Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it's simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.
In the addTask()
method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString()
method:
public void addTask(Task t) {
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
currentTasks.add(t);
// save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}
Similarly we have to retrieve the list of tasks from the preference in the onCreate()
method:
public void onCreate() {
super.onCreate();
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
You can get the ObjectSerializer
class from the Apache Pig project ObjectSerializer.java
Related Topics
Android - Cancel Asynctask Forcefully
Noclassdeffounderror For Code in an Java Library on Android
How to Grant Modify_Phone_State Permission For Apps Ran on Gingerbread
How to Detect Android App Uninstall
How to Download Google Play Services in an Android Emulator
Android - Android.View.Inflateexception: Binary Xml File Line #8: Error Inflating Class Fragment
Programmatically Switching Off Android Phone
How to Send String from One Activity to Another
How to Get Current Time from Internet in Android
Set Icon For Android Application
What Android Tools and Methods Work Best to Find Memory/Resource Leaks
Fileprovider - Illegalargumentexception: Failed to Find Configured Root
How to Display a List View in an Android Alert Dialog
How to Check If Alarmmanager Already Has an Alarm Set
Android 5.1.1 and Above - Getrunningappprocesses() Returns My Application Package Only