getDefaultShared preferences(...)没有在第一次运行不存在缓存中工作 [英] getDefaultSharedPreferences(...) doesn't work in first run without existed cache
问题描述
我有一个 preferenceActivity
保存所有我的应用程序preferences。
当我想在主
活动中使用这些preferences,我使用:
I have a PreferenceActivity
that holds all my app preferences.
When I want to use these preferences in Main
activity, I use:
prefScreen = PreferenceManager.getDefaultSharedPreferences(this);
String lang = prefScreen.getString("language_list", null);
现在,当我做到这一点,运行我的应用程序作为第一运行在设备上的一次(无缓存),它会立即崩溃。
但是,如果我叫 preferenceActivity
(使用 startActivity()
)的<$ C $的开始C>主要活动,然后返回到主
本身,它运行得很好,即使我编辑了code,然后再次运行它。
如果我手动清除应用程序缓存的问题再次发生。
我应该叫 preferenceActivity
总是在第一次运行?我缺少的东西吗?
Now, when I do that and run my app as first-run-on-device-ever (without cache), it crashes immediately.
But, if I called the PreferenceActivity
(using startActivity()
) at the beginning of Main
activity, then return to Main
itself, it runs very well, even if I edited the code and run it again.
The problem happens again if I cleared the cache of the app manually.
Should I call PreferenceActivity
always at the first run?! Am I missing something?
注意:我用登录
来证实这一点我自己。第一次运行前, prefScreen.contains(language_list)
总是等于假
。我呼吁后, preferenceActivity
,就变成真正
。
NOTE: I used Log
to confirm this to myself. Before first run, prefScreen.contains("language_list")
is always equals to false
. And after I call PreferenceActivity
, it becomes true
.
推荐答案
您必须调用setDefaultValues在主要设置使用之前的默认值
You have to call setDefaultValues in Main to set the default values before used
PreferenceManager.setDefaultValues (Context context, int resId, boolean readAgain)
这篇关于getDefaultShared preferences(...)没有在第一次运行不存在缓存中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!