7

I'm new to Android development. In my app, when a user changes a preference, a function should be called to update some variables.

This is my current code:

mypref.setOnPreferenceChangeListener(
   new OnPreferenceChangeListener() {
      public boolean onPreferenceChange(Preference arg0, Object arg1) {
         if(arg1.toString().matches("...") == false) {
            ...
            return false;
         }

         ...

         updateVariables();
         return true;
     }
});

The problem is that when updateVariables() is called, the preference value is not yet updated and the function sees the old value.

private void updateVariables()
{
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    Map<String, ?> savedKeys = sharedPref.getAll();

    for (Map.Entry<String, ?> entry : savedKeys.entrySet()) {
       // for each preference...
    }
}

What would the least invasive solution be? Thanks!

3 Answers 3

5

The second argument of onPreferenceChange() (arg1 here) is the new value. I'd suggest to just add that as an argument to updateVariables() as well and just pass the object through to work with it.

5
  • 1
    Thanks. But what if in updateVariables() I have to iterate a lot of other preferences? I would need a lot of different arguments.
    – danieleds
    Oct 8, 2011 at 6:44
  • This here just gives you the one preference value that changed. All others are the same until the callback returned. So you just have to forward the one, all others can be read by creating a normal SharedPreferences object. (Apart from that you can still use a List as an argument if you got a lot of arguments to provide)
    – user658042
    Oct 8, 2011 at 9:13
  • hmm... maybe I'm doing it wrong, but I've added an example of updateVariables(). How can I do the cycle if I add an extra argument with the updated value? How can I avoid processing the same preference 2 times (one time with the old value from SharedPreferences, one time with the new value from args)? I can only think about dirty solutions :S
    – danieleds
    Oct 8, 2011 at 9:30
  • 1
    I'm not sure if i get this in the correct way, but you can just forward key and value to the method and delete the existing key from the map/set. After that add a new one with the new value. Then execute the loop. (although i don't see why you have to iterate over all preferences when a single one changes. That seems somewhat inefficient to me - but might be that i just don't know the context)
    – user658042
    Oct 8, 2011 at 10:38
  • Great, that's a good solution :) Yes, I tried to avoid the iteration... but I couldn't find alternative ways to do what I need to do without a big rude cycle. Maybe it's because I don't know yet all the strange details of this strange and glittering Android platform :D
    – danieleds
    Oct 8, 2011 at 11:11
0

Using PreferenceFragmentCompat

public class FragmentSettings
extends PreferenceFragmentCompat
implements SharedPreferences.OnSharedPreferenceChangeListener


@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

    addPreferencesFromResource(R.xml.app_preferences);

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}


@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    switch(key)
    {
        case "KEY1":
            // DO STUFF
            break;

        case "KEY2":
            // DO STUFF
            break;
    }
}
1
  • Not sure why this was downvoted : It does call onSharedPreferenceChanged AFTER the change has been made. So it is answering correctly to the OP's problem.
    – Yahel
    Jun 26 at 11:32
0

I only found a trick to sleep just a little bit and then call to really update.

private void updateVariables() {

    new Thread() {
        public void run() {
            try {
               Thread.sleep(100); //Sleep a little bit to let Android update the Preference
            } catch (InterruptedException e) {
            }
            //Now go back to the main UI:
            getActivity().runOnUiThread
                    (new Runnable() {
                         @Override
                         public void run() {
                             //
                             //Here you do the update of your screen
                             //
                         }
                     }
                    );
        }
    }.start();

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.