I want to store more than one Integer Values in Shared Preference. Is this possible to do it?
Asked
Active
Viewed 855 times
-2
-
Yes you can add int values in arraylist and store arraylist in sp. – Piyush Jan 31 '17 at 10:29
-
possible duplicate of http://stackoverflow.com/questions/9054193/how-to-use-sharedpreferences-to-save-more-than-one-values – rafsanahmad007 Jan 31 '17 at 10:30
-
Possible duplicate of [How to use SharedPreferences to save more than one values?](http://stackoverflow.com/questions/9054193/how-to-use-sharedpreferences-to-save-more-than-one-values) – Manoj Perumarath Jan 31 '17 at 11:03
-
1Possible duplicate of [How can I store an integer array in SharedPreferences?](http://stackoverflow.com/questions/7175880/how-can-i-store-an-integer-array-in-sharedpreferences) – Sufian Feb 05 '17 at 07:41
3 Answers
2
For saving in SharedPreferences
:
public void putListInt(String key, ArrayList<Integer> intList) {
checkForNullKey(key);
Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
preferences.edit().putString(key, TextUtils.join("‚‗‚", myIntList)).apply();
}
For retrieving from SharedPreferences
:
public ArrayList<Integer> getListInt(String key) {
String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
ArrayList<Integer> newList = new ArrayList<Integer>();
for (String item : arrayToList)
newList.add(Integer.parseInt(item));
return newList;
}

Sufian
- 6,405
- 16
- 66
- 120

Muhammad Ejaz
- 43
- 2
- 9
0
You can use Set(form Java Collection) to store more than one Integer values in Shared Preferences.

Shruti
- 803
- 9
- 26
-
There is no method to putintSet("key", set); Not work for me. I don't understand the programmers logic because sawal gandum r jawab channa hota hy. – Muhammad Ejaz Feb 01 '17 at 06:19
0
Use the Gson for storing array in SharedPreferences
For storing value.
int[] list = new int[10];
String string=new Gson().toJson(list);
prefs.edit().putString("data", string).apply();
For fetching value.
String data=prefs.getString("data",null);
int [] list=new Gson().fromJson(data,int[].class);

Rahul Giradkar
- 1,818
- 1
- 17
- 28