Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - do something in activity when preferences change

I have two classes, CustomerPreferences which extends PreferenceActivity implements OnSharedPreferenceChangeListener and CustomerActivity which extends Activity. In CustomerActivity, I calculate some values. In CustomerPreferences there's a particular ListPreference I want to monitor. When the user enters CustomerPreferences--which is done via a menu option on CustomerActivity--and changes that ListPreference, then hits the back button and returns to CustomerActivity, I want to recalculate my values based on the new preference setting. If the user goes into CustomerPreferences but doesn't change the value of the ListPreference, I don't want to recalculate anything upon return to CustomerActivity.

How can I do this?

I figure I'll need to do something in CustomerPreferences.onSharedPreferenceChanged as well as maybe CustomerPreferences.onBackPressed, then probably handle something in CustomerActivity.

like image 285
Sarah Vessels Avatar asked Dec 21 '25 05:12

Sarah Vessels


1 Answers

You can handle the change in CustomerActivity's onResume() method. So after the user presses back, in onResume(), go through your preferences and recalculate your values and change your GUI representation based on the calculated values.

Sure, sometimes this will be unnecessary as the user may not have changed anything. As long as your calculations aren't too heavy this should not be cause for concern.

Another thing you can do is set a boolean in shared preferences such as preferencesChanged which will get set to true in CustomerPreferences.onSharedPreferenceChanged. Then check preferencesChanged in onResume(). If true do your recalculations. Otherwise do nothing.

Another option is to start the preferences activity for a result with startActivityForResult(). Then do the recalculations in onActivityResult() in CustomerActivity. The result value would be set in CustomerPreferences.onSharedPreferenceChanged

like image 50
Mike L. Avatar answered Dec 22 '25 19:12

Mike L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!