I have created an onSharedPreferencesChangeListener which is working correctly. I know this because when I setup the listener I logged the listener and it is triggering on a change.
However, I was getting an error when I was trying to switch the key variable (saying that I need JRE 1.7+ in order to switch a string), so I changed it to if-elseif statements.
The if-elseif statements weren’t triggering so I changed the first two to if statements and put the elseif after that (thinking that the elseif might have been the problem). Still no triggering.
The weird thing is that when I logged the event trigger, I output ““+key+”” as the string and the key value is the exact strings that I’m testing for.
Here is my code, can someone point me in the right direction please?
// logic for action when a shared preference is changed.
prefs.registerOnSharedPreferenceChangeListener( new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String TAG = "UltimateScoreboard";
if (key == "Main_Clock_Minutes") {
msMainClockStart = Long.valueOf( prefs.getString( "Main_Clock_Minutes", "0" ) ) * 60000;
Log.i( TAG, key + " changed: " + String.valueOf(msMainClockStart) );
}
if ( key == "Use_ShotClock" ) {
useShotClock = prefs.getBoolean( "Use_ShotClock", false );
if( useShotClock )
btnShotClock.setVisibility( View.VISIBLE );
else
btnShotClock.setVisibility( View.INVISIBLE );
Log.i( TAG, key );
}
else if ( key == "Shot_Clock_Seconds" ) {
msShotClockStart = Long.valueOf( prefs.getString( "Shot_Clock_Seconds", "0" ) ) * 1000;
Log.i( TAG, key + " changed: " + Long.valueOf(msShotClockStart) );
}
You must use the
String.equals()function to compare strings.==with Strings only compares memory locations.For example:
if (key.equals("Main_Clock_Minutes"))