4

I am trying to save an int array into the shared preferences.

int myInts[]={1,2,3,4};
SharedPreferences prefs = getSharedPreferences(
                        "Settings", 0);
                SharedPreferences.Editor editor = prefs
                        .edit();
                editor.putInt("savedints", myInts);

Since the putInt method does not accept int arrays, I was wondering if anyone knew another way to do this. Thanks

4 Answers 4

11

Consider JSON. JSON is well integrated into Android and you can serialize any complex type of java object. In your case the following code would be suited well.

// write
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    JSONArray arr = new JSONArray();
    arr.put(12);
    arr.put(-6);
    prefs.edit().putString("key", arr.toString());
    prefs.edit().commit();
    // read
    try {
        arr = new JSONArray(prefs.getString("key", "[]"));
        arr.getInt(1); // -6
    } catch (JSONException e) {
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

the problem with the JSON method is that I would like to change the array and there doesnt seem to be a way to do something like myInt[3]=4 because we're just stacking ints
unfortunately, yes! there is no way of doing this with the json library of the Android framework...
4

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

refer this doc:

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

4 Comments

Do you have a suggestion that I could do to have the same effect?
you can use Sqlite ...and if the data is not too large the u can put int array value one by one to sharedpreference as int value..
lets say I did the one by one int value. if I named my keys 1.2.3etc could I call it using a for loop like prefs.getInt(i,0)? Or are the keys always strings
you key should be String...you can do that if store the keys in constant file like this public static final String VAR = "var"; and public static final String VAR1 = "var1"; -------now you can use for loop to add and fetch value like this:------for(int i = 1; i <= value; i++){ String yourVarName = pref.getString(AppConstants.VAR + i, ""); }
3

You can serialize an array to String using TextUtils.join(";", myInts) and the deserialize it back using something like TextUtils. SimpleStringSplitter or implement your own TextUtils.StringSplitter.

Comments

0

If your integers are unique, perhaps you can use putStringSet (see docs). Otherwise you have to resort to serializing / formatting your integer array as String, as suggested by other answers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.