Skip to content Skip to sidebar Skip to footer

Sharedpreferences Putting An Array

how can I use this code in order to add an array and retrieve it later? can I use a simple for loop? SharedPreferences settings = getSharedPreferences('isChk', 0); SharedPrefer

Solution 1:

To store an array in sharedPreferences , you can put your array values in a String , then store this String .. and if you you want to get your array value (in our case ,stored in a string) , you get the string and parse it using StringTokenizer like this : (In my example I will store and retreive an array of Boolean)

  • Put your booleans 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);
    Boolean[] list = new Boolean[10];
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < list.length; i++) {
    str.append(list[i]).append(",");
    }
    prefs.edit().putBoolean("keys", str.toString()).commit();
    
  • Get the string and parse it using StringTokenizer:

    String savedString = prefs.getString("string", "");
    StringTokenizer st = new StringTokenizer(savedString, ",");
    Boolean[] savedList = newBoolean[10];
     for (int i = 0; i < 10; i++) {
        savedList[i] = Boolean.valueOf(st.nextToken();
      }
    

Solution 2:

Here is how u do to save Array in Shared Preferences

publicstatic boolean saveTheArray()
{
 SharedPreferences sharedpref = SharedPreferences.getDefaultSharedPreferences(this);
 SharedPreferences.Editor mEdit1 = sharedpref .edit();
 mEdit1.putInt("Status_size", array.size()); //array-> the array to be saved for(int i=0;i<array.size();i++)  
{
    mEdit1.remove("Status_" + i);
    mEdit1.putString("Status_" + i, array.get(i));  
}

return mEdit1.commit();     

}

To retriev it use the following code:

publicstaticvoidloadArray(Context mContext)
{  
SharedPreferences mShrdPref = PreferenceManager.getDefaultSharedPreferences(mContext);
array.clear();
int size = mShrdPref.getInt("Status_size", 0);  

for(int i=0;i<size;i++) 
{
    array.add(mShrdPref.getString("Status_" + i, null));
}
}

Hope it helps :)

Solution 3:

Use key names instead of isChk to get value of keys from SharedPreferences because isChk is SharedPreferences name :

keys[i] = settings.getBoolean("keys", false);

Also you are saving all values with same key keys so you only get last value which you have added. to store all values use unique keys like "keys"+i.

For more how we add Array in SharedPreferences see this post:

Save ArrayList to SharedPreferences

Post a Comment for "Sharedpreferences Putting An Array"