danieleds
danieleds

Reputation: 668

How to call a function *after* onPreferenceChange?

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!

Upvotes: 7

Views: 4501

Answers (3)

Ton
Ton

Reputation: 9736

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();

}

Upvotes: 0

MarcoGR
MarcoGR

Reputation: 37

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;
    }
}

Upvotes: 0

user658042
user658042

Reputation:

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.

Upvotes: 5

Related Questions