0

Inside for loop i am receiving the values of an array element, in the same loop how can i convert the string array into string so that I can save values in android preference. Below is my code :

Class A {

private String[] array = new String[20];

for (int i = 0; i <= count; i++) {
Log.d(TAG, "array == " + array[i]);    //Here in below log I will receive all the array values 

for (int j = 0; j <= count; j++) {             
                    String a=array[j];            
                    editor.putString("myString"+String.valueOf(j), a); 
                    editor.commit();
                    Log.d("Prefs", "Saved String");
                }

                int size= sharedPreferencesFDefault.getInt("arraySize", 0);
                String[] arrayGet = new String[size];

for (int k = 0; k < size; k++) { 
                    arrayGet[k] = sharedPreferencesFDefault.getString("myString"+String.valueOf(k), "");
                    Log.d("Prefs", "Received String" + arrayGet[k]);
                }

}
}

Thanks

Christine
  • 329
  • 1
  • 4
  • 13
  • 2
    I've answered for a [same question](http://stackoverflow.com/a/29575903/4762282). I'm always using `JSONArray`. – Ircover Apr 11 '15 at 13:06
  • 1
    Check [this](http://stackoverflow.com/questions/3876680/is-it-possible-to-add-an-array-or-object-to-sharedpreferences-on-android) – Kunu Apr 11 '15 at 13:11

1 Answers1

1

You can store but when you try to get it, you need to know positions of strings you have saved.

Class A {
    private static SharedPreferences sharedPreferencesFDefault=PreferenceManager.getDefaultSharedPreferences(this);        
    SharedPreferences.Editor editor = sharedPreferencesFDefault.edit();
    private String[] array = new String[20];

    for (int i = 0; i < array.length; i++) {             
        String a=array[i];            
        editor.putString("myString"+String.valueOf(i), a); 
        editor.commit();
    }
    //save size as well so you can get all array later
    editor.putInt("arraySize", array.length); 
    editor.commit();
}

To get it

int size= sharedPreferencesFDefault.getInt("arraySize", 0);
String[] arrayGet = new String[size];

for (int i = 0; i < size; i++) { 
    arrayGet[i] = sharedPreferencesFDefault.getString("myString"+String.valueOf(i), "");
}
Jemshit
  • 9,501
  • 5
  • 69
  • 106