Search code examples
androidsharedpreferencesonpause

SavedPreferences does not save


I am playing around a bit with android's SharedPreferences.

See my code:

@Override
    public void onPause() {
       super.onPause();
       SharedPreferences prefs = this.getSharedPreferences(
        "com.example.app", Context.MODE_PRIVATE);
         for (int i = 0; i<meds.size(); i++){
         prefs.edit().putString(String.valueOf(i), meds.get(i));
         System.out.println(meds.get(i));
         String str = prefs.getString("0", "");
         System.out.println(str);
         System.out.println(i);


    }


        prefs.edit().commit();




  }

Now I get all the prints except for that which is supposed to print str. I take it nothing is saved.

But why is that?


Solution

  • Note that prefs.edit() returns a new editor on the shared prefernces. If you do prefs.edit().commit(); the commit operates on a new editor object. You have to store a reference to the editor like that:

    @Override
    public void onPause() {
        super.onPause();
        SharedPreferences prefs = this.getSharedPreferences(
            "com.example.app", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        for (int i = 0; i<meds.size(); i++){
            editor.putString(String.valueOf(i), meds.get(i));
            System.out.println(meds.get(i));
            String str = prefs.getString("0", "");
            System.out.println(str);
            System.out.println(i);
        }
        editor.commit();
    }
    

    Otherwise nothing is saved.