Is it possible to add an array or object to SharedPreferences on Android
So from the android developer site on Data Storage:
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
So I think it is okay since it is simply just key-value pairs which are persisted.
To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:
// my list of names, icon locations
Map<String, String> nameIcons = new HashMap<String, String>();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");
SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : nameIcons.keySet()) {
// use the name as the key, and the icon as the value
keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()
You would do something similar to read the key-value pairs again. Let me know if this works.
Update: If you're using API level 11 or later, there is a method to write out a String Set
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
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);
}
}
Android ArrayList of custom objects - Save to SharedPreferences - Serializable?
Yes, you can save your composite object in shared preferences. Let's say..
Student mStudentObject = new Student();
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(mStudentObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
..and now you can retrieve your object as:
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("MyObject", "");
Student mStudentObject = gson.fromJson(json, Student.class);
For more information, click here.
If you want to get back an ArrayList
of any type object e.g. Student
, then use:
Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students = gson.fromJson(json, type);
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);
Storing Array List Object in SharedPreferences
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, "");
Type type = new TypeToken<List<ArrayObject>>() {}.getType();
List<ArrayObject> arrayList = gson.fromJson(json, type);
How to save List Object to SharedPreferences in Flutter?
You should do these steps
to save the object:
- convert your object to map with
toMap()
method- encode your map to string with
encode(...)
method- save the string to shared preferences
for restoring your object:
- decode shared preference string to a map with
decode(...)
method- use
fromJson()
method to get your object
UPDATE FULL SAMPLE
import 'dart:convert';
void main() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Encode and store data in SharedPreferences
final String encodedData = Music.encode([
Music(id: 1, ...),
Music(id: 2, ...),
Music(id: 3, ...),
]);
await prefs.setString('musics_key', encodedData);
// Fetch and decode data
final String musicsString = await prefs.getString('musics_key');
final List<Music> musics = Music.decode(musicsString);
}
class Music {
final int id;
final String name, size, rating, duration, img;
bool favorite;
Music({
this.id,
this.rating,
this.size,
this.duration,
this.name,
this.img,
this.favorite,
});
factory Music.fromJson(Map<String, dynamic> jsonData) {
return Music(
id: jsonData['id'],
rating: jsonData['rating'],
size: jsonData['size'],
duration: jsonData['duration'],
name: jsonData['name'],
img: jsonData['img'],
favorite: false,
);
}
static Map<String, dynamic> toMap(Music music) => {
'id': music.id,
'rating': music.rating,
'size': music.size,
'duration': music.duration,
'name': music.name,
'img': music.img,
'favorite': music.favorite,
};
static String encode(List<Music> musics) => json.encode(
musics
.map<Map<String, dynamic>>((music) => Music.toMap(music))
.toList(),
);
static List<Music> decode(String musics) =>
(json.decode(musics) as List<dynamic>)
.map<Music>((item) => Music.fromJson(item))
.toList();
}
how to add data from arraylist to shared preferences
Hope you know how to declare object of sharedPreference and how to use Editor object.
convert your arraylist to List<>
List<String> listTemp=tii ;
Add whole list in sharedPreference :
editor.putStringSet("key", listTemp);
editor.commit();
Retrieve list :
Set<String> set = editor.getStringSet("key", null);
Related Topics
Playing an Arbitrary Tone With Android
Android View.Getdrawingcache Returns Null, Only Null
How to Read Mms Data in Android
Android - Cancel Asynctask Forcefully
Disable Scrolling in All Mobile Devices
Warning: This Asynctask Class Should Be Static or Leaks Might Occur
How to Display the Current Value of an Android Preference in the Preference Summary
What Is Difference Between Getsupportfragmentmanager() and Getchildfragmentmanager()
Show Image View from File Path
How to Set Ringtone in Android from My Activity
How to Change Colors of a Drawable in Android
Noclassdeffounderror For Code in an Java Library on Android
Android Chrome Ignoring -Webkit-Text-Size-Adjust:None Property. Text Is Being Scaled When Zoomed Out
Android Update Activity UI from Service