How Can Write Code to Make Sharedpreferences for Array in Android

How can write code to make sharedpreferences for array in android?

putStringSet and getStringSet are only available in API 11.

Alternatively you could serialize your arrays using JSON like so:

public static void setStringArrayPref(Context context, String key, ArrayList<String> values) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray a = new JSONArray();
for (int i = 0; i < values.size(); i++) {
a.put(values.get(i));
}
if (!values.isEmpty()) {
editor.putString(key, a.toString());
} else {
editor.putString(key, null);
}
editor.commit();
}

public static ArrayList<String> getStringArrayPref(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(key, null);
ArrayList<String> urls = new ArrayList<String>();
if (json != null) {
try {
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
String url = a.optString(i);
urls.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return urls;
}

Set and retreive your URLs like so:

// store preference
ArrayList<String> list = new ArrayList<String>(Arrays.asList(urls));
setStringArrayPref(this, "urls", list);

// retrieve preference
list = getStringArrayPref(this, "urls");
urls = (String[]) list.toArray();

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

Android Shared Preferences with ArrayList

You're trying to store boolean true and false values as strings. This means you can only have two possible strings, "true" and "false". Set type containers only store unique values - there are no duplicates. So in your set you will only have up to two different values, "true" and "false".

If you want to store a list, you might want to convert that into a string somehow so that the actual values and order are preserved. Then when reading that value out, parse the string to reconstruct the list.

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.

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);
}

How do I add an int array into shared preferences?

you can add only primitive values to sharedpreference ......

refer this doc:

http://developer.android.com/reference/android/content/SharedPreferences.html



Related Topics



Leave a reply



Submit