如何获取共享首选项的值

问题描述:

我想从共享首选项中检索“entries”而不是“entryValue”。我使用这一点,它得到entryValue:如何获取共享首选项的值

String notifyInterval = PreferenceManager.getDefaultSharedPreferences(mActivity).getString(ACCUWX.Preferences.PREF_NOTIFY_INTERVAL, null); 

这里是XML和数组文件:

<ListPreference 
android:key="pref_temp_notifications" 
android:title="@string/notifications" 
android:entries="@array/pref_temp_notifications" 
android:entryValues="@array/pref_temp_notifications_values" 
android:dialogTitle="@string/notifications" 
android:defaultValue="2"/> 

<string-array name="pref_temp_notifications"> 
    <item>@string/my_current_location</item> 
    <item>@string/home_location</item> 
    <item>@string/off</item> 
</string-array> 
<string-array name="pref_temp_notifications_values"> 
    <item>0</item> 
    <item>1</item> 
    <item>2</item> 
</string-array> 

所以我想检索字符串值,而不是数字。数字是我返回并分配给我的变量notifyInterval。我如何抓取文字?

+0

为什么不直接替换'0,1,2'以字符串值 – Wozza 2011-12-30 13:31:17

+0

我不这样做,因为有我需要两个字符串值,在代码中计算的整数值,其他首选项。 – taraloca 2011-12-30 14:24:05

+0

SharedPreferences的getAll()方法将返回所有键值对。从这张地图你可以得到所有关键值。 – Yury 2011-12-30 14:36:23

您需要使用返回Map的getAll()方法,从该地图获取KeySet,该KeySet返回共享首选项的条目。

Map<String, ?> test = getAll(); 
Set keySet = test.keySet(); 

Iterator<String> keySetIter = keySet .iterator(); 
    while (keySetIter.hasNext()) { 
    String keyEntry= keySetIter.next(); 
} 
+0

我试过这个,它返回的不是存储的值。 – taraloca 2011-12-30 16:24:50

+0

我认为这就是你要找的?你知道获得共享首选项的关键吗?如果是这样,你可以使用这样的东西,如果你的值是Integer,你需要使用getInt(),而不是getBoolean(....)SharedPreferences设置= getSharedPreferences(PREFS_NAME,0); boolean silent = settings.getBoolean(“silentMode”,false); – kosa 2011-12-30 16:52:58

+0

这将返回entryValue,我需要条目。我可以在我的活动中像这样扩展PreferenceActivity,其中“key”是我的首选项:Preference pref = findPreference(key); \t \t String currentPrefValue = null; (ListPreference的实例){ \t ListPreference listPref =(ListPreference)pref; \t currentPrefValue =(listPref.getEntry())。toString(); (DEBUG_TAG,“onSharedPreferenceChanged中的当前pref值为”+ currentPrefValue); \t} – taraloca 2011-12-30 17:07:34