Following an example from Professional Android 2 Application Development I set up a pref class as follows:
//Preferences.java
public class Preferences extends PreferenceActivity{
public static final String PREF_SPEED_UNIT ="PREF_SPEED_UNIT";
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.userpreferences);
}
}
In my activity class:
// main.java
private static final int SHOW_PREFERENCES = 1;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SHOW_PREFERENCES)
updateFromPreferences();
if (resultCode == Activity.RESULT_OK) {
}
}
private void updateFromPreferences() {
Log.d(TAG, "updateFromPreferences()");
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
// Set the SpeedMode string using object reference to custom view
mSpeedMode = prefs.getString(Preferences.PREF_SPEED_UNIT, "MPH");
speedview.SpeedMode = mSpeedMode;
}
// Using have a Button view that pops the options for testing
private OnClickListener optionbuttonCL = new OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
Intent i = new Intent(context, Preferences.class);
startActivityForResult(i, SHOW_PREFERENCES);
}
};
The issue is here:
// SpeedView.java
if (SpeedMode == "MPH"){
// set speed in miles/hour
}
if (SpeedMode == "KPH"){
//set speed in kilometers/hour
}
It works, however if I switch speed modes to KPH (default is MPH), the display no longer updates.
The bewildering thing is even if SpeedMode is shown to be "MPH" or "KPH" using the Eclipse debugger, the if statements will not execute.
Here is the rest of the code:
//userpreferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference android:key="PREF_SPEED_UNIT"
android:title="Speed Unit"
android:summary="Choose between MPH or KPH"
android:entries="@array/speed_options"
android:entryValues="@array/speed_values"
android:dialogTitle="Speed Unitz"
android:defaultValue="MPH" />
</PreferenceScreen>
// arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="speed_options">
<item>MPH</item>
<item>KPH</item>
</string-array>
<string-array name="speed_values">
<item>MPH</item>
<item>KPH</item>
</string-array>
Thanks