I have an ArrayList
with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves
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
public void saveUserName(Context con,String username)
{
try
{
usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
usernameEditor = usernameSharedPreferences.edit();
usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1));
int size=USERNAME.size();//USERNAME is arrayList
usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
usernameEditor.commit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void loadUserName(Context con)
{
try
{
usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
USERNAME.clear();
for(int i=0;i<size;i++)
{
String username1="";
username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
USERNAME.add(username1);
}
usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
username.setAdapter(usernameArrayAdapter);
username.setThreshold(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
You can save String and custom array list using Gson library.
=>First you need to create function to save array list to SharedPreferences.
public void saveListInLocal(ArrayList<String> list, String key) {
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
=> You need to create function to get array list from SharedPreferences.
public ArrayList<String> getListFromLocal(String key)
{
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
=> How to call save and retrieve array list function.
ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());
=> Don't forgot to add gson library in you app level build.gradle.
implementation 'com.google.code.gson:gson:2.8.2'
You can use serialization or Gson library to convert list to string and vice versa and then save string in preferences.
Using google's Gson library:
//Converting list to string
new Gson().toJson(list);
//Converting string to list
new Gson().fromJson(listString, CustomObjectsList.class);
Using Java serialization:
//Converting list to string
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
oos.flush();
String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
oos.close();
bos.close();
return string;
//Converting string to list
byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
ObjectInputStream ois = new ObjectInputStream(bis);
Object clone = ois.readObject();
ois.close();
bis.close();
return (CustomObjectsList) clone;
Also with Kotlin:
fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
putString(key, list?.joinToString(",") ?: "")
return this
}
fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
val value = getString(key, null)
if (value.isNullOrBlank())
return defValue
return ArrayList (value.split(",").map { it.toInt() })
}
Use this custom class:
public class SharedPreferencesUtil {
public static void pushStringList(SharedPreferences sharedPref,
List<String> list, String uniqueListName) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(uniqueListName + "_size", list.size());
for (int i = 0; i < list.size(); i++) {
editor.remove(uniqueListName + i);
editor.putString(uniqueListName + i, list.get(i));
}
editor.apply();
}
public static List<String> pullStringList(SharedPreferences sharedPref,
String uniqueListName) {
List<String> result = new ArrayList<>();
int size = sharedPref.getInt(uniqueListName + "_size", 0);
for (int i = 0; i < size; i++) {
result.add(sharedPref.getString(uniqueListName + i, null));
}
return result;
}
}
How to use:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));