2015-05-24 24 views
2

我正在製作一個應用程序,無論何時您進入活動時,它都會播放聲音文件。我更喜歡你可以改變它播放的聲音文件。下面是偏好活動代碼:偏好管理器沒有從用戶偏好中獲得價值

<?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> 

,這裏是數組文件的東西:

<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> 

而這裏的onCreate用於播放聲音文件的活動:

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); 
} 

我的問題是,SharedPreferences沒有從用戶選擇的值中獲​​取值。
因此,mediaplayer從不被創建,導致應用程序在我退出該活動時崩潰,因爲我在onStop()方法中釋放了MediaPlayer。
我的SharedPreference/PreferenceManager的構造函數是否正確?
關於我在做什麼錯誤或者我如何解決它的任何想法?

回答

3

嘗試使用equals()而不是==檢查字符串。

if(choiceSound.equals("a")) 

代替

if(choiceSound == "a") 

'==' 比較的對象的參考。你想檢查它的價值。