Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store an integer array in SharedPreferences?

I want to save/recall an integer array using SharedPreferences. Is this possible?

like image 436
user878813 Avatar asked Aug 24 '11 13:08

user878813


People also ask

Can we store array in SharedPreferences?

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.

Can we store objects in SharedPreferences?

We can store fields of any Object to shared preference by serializing the object to String.


4 Answers

You can try to do it this way:

  • Put your integers into a string, delimiting every int by a character, for example a comma, and then save them as a string:

    SharedPreferences prefs = getPreferences(MODE_PRIVATE); int[] list = new int[10]; StringBuilder str = new StringBuilder(); for (int i = 0; i < list.length; i++) {     str.append(list[i]).append(","); } prefs.edit().putString("string", str.toString()); 
  • Get the string and parse it using StringTokenizer:

    String savedString = prefs.getString("string", ""); StringTokenizer st = new StringTokenizer(savedString, ","); int[] savedList = new int[10]; for (int i = 0; i < 10; i++) {     savedList[i] = Integer.parseInt(st.nextToken()); } 
like image 95
Egor Avatar answered Sep 17 '22 15:09

Egor


You can't put Arrays in SharedPreferences, but you can workaround:

private static final String LEN_PREFIX = "Count_"; private static final String VAL_PREFIX = "IntValue_"; public void storeIntArray(String name, int[] array){     SharedPreferences.Editor edit= mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE).edit();     edit.putInt(LEN_PREFIX + name, array.length);     int count = 0;     for (int i: array){         edit.putInt(VAL_PREFIX + name + count++, i);     }     edit.commit(); } public int[] getFromPrefs(String name){     int[] ret;     SharedPreferences prefs = mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE);     int count = prefs.getInt(LEN_PREFIX + name, 0);     ret = new int[count];     for (int i = 0; i < count; i++){         ret[i] = prefs.getInt(VAL_PREFIX+ name + i, i);     }     return ret; } 
like image 42
Rafael T Avatar answered Sep 21 '22 15:09

Rafael T


Here's my version, based on Egor's answer. I prefer not to use StringBuilder unless I'm building an enourmous string, but thanks to Egor for using StringTokenizer -- haven't made much use of this in the past, but it's very handy! FYI, this went in my Utility class:

public static void saveIntListPrefs(
    String name, Activity activity, List<Integer> list)
{
  String s = "";
  for (Integer i : list) {
    s += i + ",";
  }

  Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
  editor.putString(name, s);
  editor.commit();
}

public static ArrayList<Integer> readIntArrayPrefs(String name, Activity activity)
{
  SharedPreferences prefs = activity.getPreferences(Context.MODE_PRIVATE);
  String s = prefs.getString(name, "");
  StringTokenizer st = new StringTokenizer(s, ",");
  ArrayList<Integer> result = new ArrayList<Integer>();
  while (st.hasMoreTokens()) {
    result.add(Integer.parseInt(st.nextToken()));
  }
  return result;
}
like image 39
Nick Bolton Avatar answered Sep 21 '22 15:09

Nick Bolton


Two solutions:

(1) Use http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

It has split/join functions that let you join and split the integers in one liners:

StringUtils.join([1, 2, 3], ';')  = "1;2;3"
StringUtils.split("1;2;3", ';')   = ["1", "2", "3"]

You'd still have to convert the strings back to integers, though.

Actually, for splitting java.lang.String.split() will work just as fine: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

(2) Use the SharedPreferences.putStringSet() (API 11):

    SharedPreferences.Editor editor = preferences.edit();
    int count = this.intSet.size();
    if (count > 0) {
        Set<String> theSet = new HashSet<String>();
        for (Long l : this.intSet) {
            theSet.add(String.valueOf(l));
        }
        editor.putStringSet(PREFS_KEY, theSet);
    } else {
        editor.remove(PREFS_KEY);
    }
    editor.commit();

And to get it back:

    Set<String> theSet = this.preferences.getStringSet(PREFS_KEY, null);
    if (theSet != null && !theSet.isEmpty()) {
        this.intSet.clear();
        for (String s : theSet) {
            this.intSet.add(Integer.valueOf(s));
        }
    }

This code does not catch the NPEs or NumberFormatExceptions because the intSet is otherwise assured to not contain any nulls. But of course, if you cannot assure that in your code you should surround this with a try/catch.

like image 23
Risadinha Avatar answered Sep 18 '22 15:09

Risadinha