How to add int array to general settings?

I am trying to save an int array in general settings.

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 knows any other way to do this. Thanks

+4
source share
4 answers

you can add only primitive values ​​in sharedpreference ......

refer to this document:

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

+4
source

Consider JSON. JSON is well integrated in Android, and you can serialize any complex type of Java object. In your case, the following code is suitable.

 // 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(); } 
+11
source

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

+3
source

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

0
source

Source: https://habr.com/ru/post/1369116/


All Articles