2013-01-06 16 views
0

我不知道我在做什麼錯誤,並希望得到一些幫助,請。偏好管理器和共享首選項

在我的主要活動的onCreate方法我有這樣的:

// set the default preferences 
    PreferenceManager.setDefaultValues(context, R.xml.preferences, false); 

    // get the preferences 
    prefs = getPreferences(MODE_PRIVATE); 

    // Load the values or defaults from the SharedPreferences 
    msMainClockStart = prefs.getLong("Main_Clock_Minutes", 0); 
    useShotClock = prefs.getBoolean("Use_ShotClock", false); 
    msShotClockStart = prefs.getLong("Shot_Clock_Seconds", 20000); 
    tvPeriodPrefix = prefs.getString("Period_Prefix", "P"); 
    valMaxPeriods = prefs.getInt("Max_Periods", 4); 

在我RES/XML /的preferences.xml文件我有以下

<?xml version="1.0" encoding="utf-8"?> 

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 
<EditTextPreference 
    android:key="Main_Clock_Minutes" 
    android:positiveButtonText="SAVE" 
    android:negativeButtonText="CANCEL" 
    android:title="Main Clock (minutes)" 
    android:defaultValue="480000" 
    android:summary="How many minutes for the main clock."/> 

<CheckBoxPreference 
    android:key="Use_ShotClock" 
    android:title="Enable Shot Clock" 
    android:defaultValue="true"/> 

<EditTextPreference 
    android:key="Shot_Clock_Seconds" 
    android:title="Shot Clock (seconds)" 
    android:summary="How many seconds for the shot clock." 
    android:defaultValue="30000"/> 

<EditTextPreference 
    android:key="Period_Prefix" 
    android:title="Period Prefix (e.g. Q, Shift, Period)" 
    android:defaultValue="Q"/> 

<EditTextPreference 
    android:key="Max_Periods" 
    android:title="Maximum number of periods" 
    android:defaultValue="4"/> 

對於一些原因是默認值沒有從xml文件讀取/加載。輸入到正在使用的getLong()方法或getBool()方法中的默認值。

有誰知道爲什麼?

編輯@Gunnar卡爾森

變爲getDefaultSharedPreferences後,我越來越在行121錯誤是這個:

msMainClockStart = prefs.getLong("Main_Clock_Minutes", 0); 

的錯誤說:「不能從長轉換爲字符串。但是msMainClockStart是一個漫長而prefs.getLong()返回一個長,所以我不知道爲什麼它不工作。

回答

0

既然你有

0設置首選項

使用

prefs = PreferenceManager.getDefaultSharedPreferences(context) 

檢索的偏好,而不是getPreferences()

+0

感謝那@Gunnar Karlsson。我編輯了我原來的帖子,並顯示一條錯誤消息,說明我沒有收到。 –

+0

prefs.getLong(...)拋出一個ClassCastException,如果存在不是很長的首選項。如果使用prefs.getString(「Main_Clock_Minutes」,0),您是否嘗試打印該值? – joel

+0

嘗試打印它在哪裏/如何? –

0

爲了使用PreferenceManager我發現了兩個選項。首先是我可以創建一個偏好子類,或者另一個是將它保存爲一個字符串,然後將其轉換爲一個Long。

下面是代碼:

// set the default preferences 
    PreferenceManager.setDefaultValues(context, R.xml.preferences, false); 

    // get the preferences 
    prefs = PreferenceManager.getDefaultSharedPreferences(context); 

    // Load the values or defaults from the SharedPreferences 
    msMainClockStart = Long.valueOf(prefs.getString("Main_Clock_Minutes", "0")) * 60000; 

這完美地工作。