Search code examples
androidandroid-intentsharedpreferencesonresume

Updating TextView in First Activity according to changes in SecondActivity


I have two activities: ActivityOne ActivityTwo

ActivityOne opens ActivityTwo

Intent i = new Intent(ActivityOne .this,ActivityTwo.class);  
startActivity(i);

ActivityTwo updates some value MyValue in SharedPrefences. ActivityOne has some TextView field that shows the value of MyValue.

After I close the ActivityTwo I want ActivityOne IMMEDIATELY to update the TextView according to the new value of MyValue (that was changed in ActivityTwo).

I tried to call to SharedPrefernces and update the TextView view in OnResume() function in ActivityOne, but somehow it doesn't get called.

Any ideas?

Thank you

More Code:

ActivityTwo updating MyValue:

@Override
protected void onStop() {
    super.onStop();
    SharedPreferences settings = getSharedPreferences(Settings.sharedPrefencesForSettingsName,0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("MyValue", unspecified.isChecked());
    editor.commit();
}

ActivityOne updating TextView:

if (settings.getBoolean("MyValue", true)) {
    textViewMine.setText("SomeText");

Solution

  • According to the Android's Coordinating activities documentation, onStop() method of ActivityTwo is executing after onResume() of ActivityOne and that's why you are not getting the updated value from SharedPreference.

    Now to solve the problem, move those code snippet from onStop() method to onPause() method as follows...

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences settings = getSharedPreferences(Settings.sharedPrefencesForSettingsName,0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("MyValue", unspecified.isChecked());
        editor.commit();
    }