Put and Get String Array from Shared Preferences

Put and get String array from shared preferences

You can create your own String representation of the array like this:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());

Then when you get the String from SharedPreferences simply parse it like this:

String[] playlists = playlist.split(",");

This should do the job.

Storing a String array in the SharedPreferences

Write methods to read and write a serialized array. This shouldn't be too difficult. Just flatten the array of strings into a single string that you store in the preferences. Another option would be to convert the array into an XML structure that you then store in the preferences, but that is probably overkill.

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 store data as array in getStringList(Shared Preference) in Flutter

I think you are mistaken about what setStringList does. All it does is saving the list you give to it. It does not add to an existing list, or check contents of the lists.

If you want a specific logic, like adding to the list or removing duplicates, you need to get the list, manipulate the list as you see fit and then set this list.

Adding an item to arralist which is already saved in shared preferences in android

as I see in your code, you create a whole new ArrayLists cartArrayListID, cartArrayListName , ..etc everytime, and then you put the new value into it, after that you save it in SharedPreferences which in turn will replace the old one saved in it with your new one, so you have to:

  1. get the corresponding ArrayList from Shared preferences at first.(for ex. cartArrayListName)
  2. save it in a new array called cartArrayListID.
  3. put the new values in this new array.
  4. save it back in SharedPreferences.

Retrieving values from a SharedPreferences string set

you can find your answer here :
Follow the link

From API level 11 you can use the putStringSet and getStringSet to
store/retrieve string sets:

SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();

SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set<String> someStringSet = pref.getStringSet(SOME_KEY);

The set interface has method which are as follows :

add() : Which allow to add an object to the collection..

clear() :
Remove all object from the collection.

size() : Return the size of
element of collection.

isEmpty() : Return true if the collection has
element.

iterator() : Return an iterator object which is used to
retrieve element from collection.

contains() : Returns true if the
element is from specified collection.

Example of java set interface.

Set s=new TreeSet();
s.add(10);
s.add(30);
s.add(98);
s.add(80);
s.add(10); //duplicate value
s.add(99);
Iterator it=s.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

How to save and retrieve an arraylist of strings with the same order, using shared preferences

If you're really interested on doing that using SharedPreferences instead of a database, you could try to save the Strings using their position on the array as the key on the preferences file.

You can achieve that with the snippet below:

private String prefName = "preferences";

/**
* Save the arraylist of Strings in a preferences file.
*/
public void saveArray(Context context, ArrayList<String> myArray) {
SharedPreferences sharedPref = context.getSharedPreferences(prefName,Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();

for (int i = 0; i < myArray.size(); i++) {
editor.putString(String.valueOf(i), myArray.get(i));
}

editor.commit();
}

/**
* Reads the saved contents in order.
*/
public ArrayList<String> readArray(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(prefName,Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();

int size = sharedPref.getAll().size();
ArrayList<String> ret = new ArrayList<>();

for (int i = 0; i < myArray.size(); i++) {
ret.add(i,sharedPref.getString(String.valueOf(i)));
}

return ret;
}

The preference file should look something like this:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="0">My String</string>
<string name="1">My second String</string>
</map>


Related Topics



Leave a reply



Submit