0

I want to evaluate checkboxpreference, tried some method from here but non of it worked. I need to get the value in the OnSharedPreferenceChangeListener, but not in PreferenceActivity. It gives an error like: ava.lang.ClassCastException: android.app.SharedPreferencesImpl cannot be cast to android.support.v7.preference.CheckBoxPreference Could somebody explain the problem?

sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                Log.d(MainActivity.this.getClass().getSimpleName(), "Einstellungen wurde geändert.");
                prefsChanged = true;
                if(key.equals("use_gps")) {
                    //TODO: CheckBox evaluate and LocationUpdate start or remove if it's not checked
CheckBoxPreference preference = (CheckBoxPreference) getSharedPreferences("use_gps", MODE_PRIVATE);
                 if(preference.isChecked()) {
                     requestLocationUpdates();
                     Log.d(getClass().getSimpleName(), "preference ischecked");
                 } else {
                     removeLocationUpdates();
                     Log.d(getClass().getSimpleName(), " preference isnotchecked");
                 }


                }

            }
        };

Thanks for all the help, solution was in MAinActivity onCreate():

if(key.equals("use_gps")) {
                    //TODO: CheckBox auswerten udn ggfs. Standortbestimmung starten oder stoppen
                    boolean checkbox = sharedPreferences.getBoolean("use_gps", true);
                    if (checkbox == true){
                        Toast.makeText(MainActivity.this, "true", Toast.LENGTH_LONG).show();
                        requestLocationUpdates();
                    } else {
                        Toast.makeText(MainActivity.this, "false", Toast.LENGTH_LONG).show();
                        removeLocationUpdates();
                    }

                }

            }
TechDuck
  • 17
  • 6
  • Congratulation on finding the solution! But you need to move the answer from the question and make an answer from it, then you can mark it as accepted answer. Other than that is good ;) – ישו אוהב אותך Jun 18 '19 at 01:04
  • The solution you provided won't update when the value of the preference is changed, as the question mentions you want to do something when the value is changed using some kind of listner but this answer snippet doesn't use any Listener. – FutureJJ Jun 18 '19 at 05:11

1 Answers1

0

This should help, instead of using OnSharedPreferenceChangeListener(), use registerOnSharedPreferenceChangeListener() to link listener to the any of your preference outside of the Preference an

Code snippet for the non-preference Activity where you want to attach the listener for a preference:

SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);

prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener()
{
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
    {
       Log.v("CHANGE ", "YES");

       boolean use_gps_stat = sharedPreferences.getBoolean("use_gps", true);

       if(key == "use_gps")
       {
           Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
           if(use_gps_stat)
           {
               Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_LONG).show();

               requestLocationUpdates();
               Log.d(getClass().getSimpleName(), "preference ischecked");
           }
           else
           {
               Toast.makeText(getApplicationContext(), "Unchecked", Toast.LENGTH_LONG).show();

               removeLocationUpdates();
               Log.d(getClass().getSimpleName(), " preference isnotchecked");
           }
       }
    }
});

In your preference activity add this to overriden onCreate:

bindPreferenceSummaryToValue_CheckBox(findPreference("use_gps"));

So it should look like this:

public static class MainPreferenceFragment extends PreferenceFragment 
{
    @Override
    public void onCreate(final Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);      
        bindPreferenceSummaryToValue_CheckBox(
                         findPreference("use_gps"));
    .
    .
    .

And add bindPreferenceSummaryToValue_CheckBox outside onCreate:

private static void bindPreferenceSummaryToValue_CheckBox(Preference preference)
{
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getBoolean(preference.getKey(), true));
}

For sBindPreferenceSummaryToValueListener simply add to the class extending to AppCompatPreferenceActivity:

private static Preference.OnPreferenceChangeListener
        sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener()
{
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue)
    {
        //Do something on prefernce change.
        return true;
    }
};

I recently tried this code structure and worked, if there are any queries let me know down in the comments.

FutureJJ
  • 2,368
  • 1
  • 19
  • 30