androidsharedpreferencesandroid-sharedpreferences

Edit sharedPreferences with two different activities to affect change in third activity


I know all about sharedPreferences, but I am confused with this. I know to put things into sharedPreferences, you do this:

Let's say this is activity A:

SharedPreferences preferences=getSharedPreferences("numbers",MODE_PRIVATE);
SharedPreferences.Editor edit=preferences.edit();
String a=ed.getText().toString();
String b=ed1.getText().toString();
editor.putString("num1",a);
editor.putString("num2",b);
editor.apply();

and to get it out in Activity B,

SharedPreferences preferences=getSharedPreferences("numbers",MODE_PRIVATE);
String numberOne=preferences.getString("num1","");
String numberTwo=preferences.getString("num2","");

and then we could set a textView in activity B as :

TextView both;
both.setText(numberOne + " " + numberTwo);

but what if I want to edit what is in the sharedPreferences in Activity C?? I was looking online on how to do that and this article here

http://codetheory.in/android-application-data-storage-sharedpreferences/

it said you only had to call it again but with a different string value like so

Activity C:

SharedPreferences preferences=getSharedPreferences("numbers",MODE_PRIVATE);
SharedPreferences.Editor edit=preferences.edit();
String c=ed3.getText().toString();
String d=ed4.getText().toString();
editor.putString("num1",c);
editor.putString("num2",d);
editor.apply();

and when this is done, it should update add in Activity B as 29 and not 12 any more. But that is where my problem is, it does not edit the sharedPreferences. Is there another way to do this? Why won't it update the addition in activity B?


Solution

  • You are probably are loading those values in onCreate()

    That method only gets called one for the Activity lifetime. When you rotate the phone the Activity gets destroyed and rebuilt, calling onCreate() again.

    A possible solution is to load the values in onResume() so that way you will have them as soon as you come back from the other activity.