2015-05-24 25 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") 

'==' 比较的对象的参考。你想检查它的价值。