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 ListObject 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);
}
}
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 the arrayList data in SharedPreferences?
Try this:
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(mArrayList1);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
//Retrieve the values
Set<String> set = new HashSet<String>();
set = myScores.getStringSet("key", null);
This question already answered here Save ArrayList to SharedPreferences
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();
}
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();
}
}
Here you change the taskclass as itemclass.
How to save Array list with model class in shared preference?
Hey I made this easy methods for Save & Get any custom model's ArrayList into SharedPreferences
.
Gson dependency required for this:
implementation 'com.google.code.gson:gson:2.8.5'
Save any custom list into SharedPreferences
:
public void saveMyPhotos(ArrayList<PhotoInfo> imagelist ) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
try {
Gson gson = new Gson();
String json = gson.toJson(imagelist);
editor.putString("MyPhotos", json);
editor.commit(); // This line is IMPORTANT !!!
} catch (Exception e) {
e.printStackTrace();
}
}
Get all my saved photos from SharedPreferences
:
private ArrayList<PhotoInfo> getAllSavedMyPhotos() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = prefs.getString("MyPhotos", null);
Type type = new TypeToken<ArrayList<PhotoInfo>>() {}.getType();
return gson.fromJson(json, type);
}
override arraylist on shared preferences
As per my understanding,
1. you have written SharedPreferences.Editor
inside saveArrayList()
.
2. On every single time this method called, you create a new Editor and it replaces the
previous one.
3. SharedPreferences stores in key-value pair and you are storing data in the same key
every time. (It Replaces previous values with new ones)
4. Your code might be correct for data but the flow is wrong. Try to work on your code-
flow.
Hope it helps. :)
Related Topics
How to Create a Transparent Activity on Android
How to Send an Object from One Android Activity to Another Using Intents
How to Check Visibility of Software Keyboard in Android
Null Pointer Exception - Findviewbyid()
How to Load an Imageview by Url in Android
Android "Only the Original Thread That Created a View Hierarchy Can Touch Its Views."
Fling Gesture Detection on Grid Layout
How to Access My Localhost from My Android Device
Detect Whether There Is an Internet Connection Available on Android
How to Put a Listview into a Scrollview Without It Collapsing
How to Connect to Android With Adb Over Tcp
How to Make an Imageview With Rounded Corners
Auto Scale Textview Text to Fit Within Bounds
All Com.Android.Support Libraries Must Use the Exact Same Version Specification
How to Make an Android Spinner With Initial Text "Select One"