Search code examples
javaandroidandroid-studiopreferences

How do I check the value of a preference after using OnPreferenceChangeListener?


At the moment, I am using an OnPreferenceChangeListener to check when the user changes the ListPreference in my app (code below) and printing a line to check this.

final Preference audioCodec = findPreference("codec");
      assert audioCodec != null;
      audioCodec.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
            System.out.println("Clicked");
     return true;
   }
});

I tried to include the if statement below to check when the user changes to a specific value.

 if (newValue == "1") {
    System.out.println("Clicked");
 }

However, this does not work. As I understand it, Object newValue is the new selected option, so in my case the value of Audio Codec 1, 2 or 3, which is 1, 2 or 3 respectively. I tried to cast newValue to an int but this also did not work.

I have included my listEntries and values below.

 <!-- Audio codec list  -->
<string-array name="codecListArray">
    <item>Audio codec 1</item>
    <item>Audio codec 2</item>
    <item>Audio codec 3</item>
</string-array>

<string-array name="codecListValues">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

I'm really stuck with this so any help would be really appreciated, figuring this out will pretty much finish my app. Please let me know if you need more information.


Solution

  • First your if statement checking is wrong because, new values is an object:

    do this:

    String value = (String)newValue;
     if (value.equals("1")) {
        System.out.println("Clicked");
     }