Gene
Gene

Reputation: 2218

SharedPreferences not saving after commit

Hi i have the following codes that stores an arraylist into a list then save it into SharedPreference. But when i re-run the app, the values are gone and no matter how many times i invoke adding more elements into the arraylist, it will only invoke once. The following is my codes:

  //debug usage
    Button z = (Button)findViewById(R.id.button3);
    z.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            testres.add("1");
            testres.add("2");
            testres.add("3");
        }
    });



    SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);
    SharedPreferences.Editor edit=prefs.edit();

    Set<String> set = new HashSet<String>();
    set.addAll(testres);
    edit.putStringSet("yourKey", set);
    edit.commit();

And this is how i retrieve:

 SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);
    Set<String> set = prefs.getStringSet("yourKey", null);
    List<String> sample= new ArrayList<String>(set);
    testres = new ArrayList<String> (set);

    for(int i =0; i<testres.size();i++){
        System.out.println("Printing: "+testres.get(i));
    }

No matter how many times i invoke onclick, the testres will have only 1,2,3 in the arraylist and if i restart the app, the elements in the arraylist is gone. Do advise thank you so much!

Update: I managed to retrieve my values on start based on the answers below but still unable to add more elements into the arraylist. The arraylist is stuck with elements 1,2,3 . Do advise.

Upvotes: 0

Views: 117

Answers (2)

cocoa
cocoa

Reputation: 398

SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();


Button z = (Button)findViewById(R.id.button3);
z.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {

        testres.add("1");
        testres.add("2");
        testres.add("3");
        Set<String> set = new HashSet<String>();
set.addAll(testres);
edit.putStringSet("yourKey", set);
edit.commit();
    }
});

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

No matter how many times i invoke onclick, the testres will have only 1,2,3 in the arraylist and if i restart the app

Because of you are saving values in SharedPreferences on Activity start which only save ArrayList with default values.

To save testres with items you have added on Button click also use SharedPreferences related code inside onClick method after adding items in ArrayList.

        @Override
        public void onClick(View arg0) {
            testres.add("1");
            testres.add("2");
            testres.add("3");
            //... save testres ArrayList in SharedPreferences here
        }

Upvotes: 2

Related Questions