I'm making an app where whenever you go to an activity, it plays a sound file. I made a preference in which you can change the sound file it plays. Here's the code for the Preference activity:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference android:title="Sound"
android:summary="Pick the sound!"
android:key="soundChoice"
android:defaultValue="a"
android:entries="@array/soundList"
android:entryValues="@array/soundValues" />
</PreferenceScreen>
and here is the array file stuff:
<string-array name="soundList">
<item>Sound 1</item>
<item>Sound 2</item>
<item>Sound 3</item>
<item>Sound 4</item>
</string-array>
<string-array name="soundValues">
<item>a</item>
<item>b</item>
<item>c</item>
<item>d</item>
</string-array>
and here is the onCreate for the Activity that plays the sound file:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
//Have also tried using "this" instead of "getBaseContext(). Same result.
String choiceSound = SP.getString("soundChoice","a");
// TODO
if(choiceSound == "a"){
mediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mediaPlayer.start();
}
else if(choiceSound == "b") {
mediaPlayer = MediaPlayer.create(this, R.raw.sound2);
mediaPlayer.start();
}
setContentView(R.layout.activity_sounder);
}
My problem is, the SharedPreferences is not getting the value from whatever the user selected.
So the mediaplayer is never being created, causing the app to crash whenever I exit the activity because I release the MediaPlayer in the onStop() method.
Is my constructor for the SharedPreference/PreferenceManager correct?
Any ideas on what I am doing wrong or how I could fix it?
答案 0 :(得分:3)
Try checking your strings with equals() instead of ==.
if(choiceSound.equals("a"))
instead of
if(choiceSound == "a")
'==' compares for the reference of the object. you want to check for the value of it.