Sean
Sean

Reputation: 1123

How do I add an int array into shared preferences?

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

Upvotes: 4

Views: 6363

Answers (4)

AZ13
AZ13

Reputation: 14517

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

Upvotes: 11

Andree
Andree

Reputation: 3103

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.

Upvotes: 0

Michael
Michael

Reputation: 54705

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.

Upvotes: 3

Vineet Shukla
Vineet Shukla

Reputation: 24031

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

refer this doc:

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

Upvotes: 4

Related Questions