Question

I'm trying to save a string in preference by adding it to the editor when a user press a button. Then i'm trying to retreieve the strings from the preference and turn it into an arrayList.

in onCreate

 this.context = getApplicationContext();
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

         int size = updatableList.size();
         editor.putInt("list_size", size);

         for (int i = 0; i < size; i++) {
             ((SharedPreferences) editor).getString("list_"+i, updatableList.get(i));
         }       
         editor.commit();

Later in the application

               updatableList.add(picturePath);
               i=i++;   
               //saving path to preference********
             SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
             ((Editor) editor).putString("list_"+i, picturePath);
             editor.commit();

It says the prefs later in the application is unused which i think is odd because i thought it told it to putString. The application crashes when it gets to there. Why does my prefs later in the application get used?

Was it helpful?

Solution

I see a main problem here and it's the following line:

i=i++;

This will not change i at all. You're telling it to increment i but at the same time setting i to the value prior to incrementing it. i++; is what you want.

Also I'd suggest using SharedPreferences.Editor.putStringSet() instead of putString() - that way you don't need to care about size and so on.

OTHER TIPS

Are you trying to getString or putString here

for (int i = 0; i < size; i++) {
         ((SharedPreferences) editor).getString("list_"+i, updatableList.get(i));
     } 

Cos the code before this, does a putInt.

SharedPreference works like a key value pair. If the key is not found, it returns the default value.

From the above code, you are first trying to getString and later trying to putString. So the initial get will return default value.

Also, you have mentioned that the code crashes. Do you mind pasting the crash log.

In saving pref try it like this snippet

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString("KEY", "value");
edit.commit();

And to fetch it

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getString("KEY", "defaultValue");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top