gpt4 book ai didi

android - 首选项管理器未从用户首选项中获取值(value)

转载 作者:搜寻专家 更新时间:2023-11-01 08:43:40 24 4
gpt4 key购买 nike

我正在制作一个应用程序,无论何时你去参加 Activity ,它都会播放一个声音文件。我做了一个偏好,您可以在其中更改它播放的声音文件。这是首选项 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>

这是数组文件的内容:

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

这是播放声音文件的 Activity 的 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 没有从用户选择的任何内容中获取值。
因此永远不会创建媒体播放器,导致应用程序在我退出 Activity 时崩溃,因为我在 onStop 中释放了 MediaPlayer () 方法。
我的 SharedPreference/PreferenceManager 构造函数是否正确?
关于我做错了什么或如何修复它有什么想法吗?

最佳答案

尝试使用 equals() 而不是 == 检查字符串。

if(choiceSound.equals("a"))

代替

if(choiceSound == "a")

'==' 比较对象的引用。你想检查它的值(value)。

关于android - 首选项管理器未从用户首选项中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com