我需要在首选项 XML 中设置的默认值在第一次运行时可用。
这在某些手机中有效,但其他一些手机(例如 Samsung)表现得非常奇怪。
在我的特殊情况下,以下代码:
String key = "@string/timeout_key"
timeout = Integer.valueOf(prefs.getString(key, "10"));
保持返回(到 timeout
)默认值“10”(作为第二个参数传递给 prefs.getString()
),尽管首选项 XML 指定:
android:defaultValue="5"
字符串“timeout_key”存在,我可以验证它是否被正确读取。
我目前的“手动解决方法”是调用设置编辑器,重新键入设置并按确定。
有没有办法以编程方式执行此操作?
最佳答案
SharedPreferences.getString()方法有问题,不会返回 android:defaultValue
。如果读取失败,它只会返回第二个参数。要解决此问题,请将 null 放入第二个参数中:
timeout = Integer.valueOf(prefs.getString(key, null));
这当然会在你安装应用程序后第一次调用它时抛出异常,所以你要做的是将它包含在 try
中,当捕获异常时,写下你的默认值(那个在你的 android:defaultValue 中,最初打算在 Android 没有问题的情况下使用):
try {
timeout = Integer.valueOf(prefs.getString(key, null));
}
catch (Exception e) {
Editor editor = prefs.edit();
editor.putString(key, Integer.toString(defaultValue));
editor.commit();
}
丑陋,但有效。
关于android:defaultValue 在某些手机上不工作 - 解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7842707/