2013-02-13 71 views
1

我有一個PreferenceActivity P,它將值存儲到SharedPreferences中。這是行得通的 - 我可以從列表中進行選擇,並且彙總值可以正確顯示。SharedPreferences正在恢復爲onResume中的默認值而不是保存的SharedPreferences值

的問題是,當我試圖到活動A.內訪問SharedPreference值默認值被加載,而不是存儲的值。之後只有我從活動A訪問PreferenceActivity,最新的SharedPreference值可供活動A使用。關於如何解決此問題的任何建議?有沒有選擇使用PreferenceManager.getDefaultSharedPreferences?

這裏是PreferenceActivity大量代碼(我略去了對onSharedPreferenceChanged聽衆):

public class P extends PreferenceActivity { 
public static String KEY_PREF_show_watch_areas, KEY_PREF_time_format, KEY_PREF_date_format; 
String PREF_show_watch_areas, PREF_time_format, PREF_date_format; 
static SharedPreferences sharedPrefs; 
Preference pref_show_watch_areas=null; 
ListPreference pref_time_format=null, pref_date_format=null; 

@SuppressWarnings("deprecation") 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
    KEY_PREF_show_watch_areas = getString(R.string.key_pref_show_watch_areas); 
    KEY_PREF_time_format = getString(R.string.key_pref_time_format); 
    KEY_PREF_date_format = getString(R.string.key_pref_date_format); 
    PREF_show_watch_areas = getString(R.string.pref_show_watch_areas); 
    PREF_time_format = getString(R.string.pref_time_format); 
    PREF_date_format = getString(R.string.pref_date_format); 

//Load up the preference items (from XML) 
    addPreferencesFromResource(R.xml.preferences); 

    //DATE pref 
    pref_date_format = (ListPreference) findPreference(KEY_PREF_date_format); //Set summary to user selected value 
    pref_date_format.setSummary(pref_date_format.getEntry()); 

    //TIME pref 
    pref_time_format = (ListPreference) findPreference(KEY_PREF_time_format); //Set summary to show user selected value 
    pref_time_format.setSummary(pref_time_format.getEntry()); 

    } 

} // [END P] 

這裏是在的onResume活動答:

@Override 
    protected void onResume() { 
    super.onResume(); 

    SharedPreferences sharedPrefsResume = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
    dateFormatPref = sharedPrefsResume.getString(P.KEY_PREF_date_format, "d-MMM-yy"); 
    timeFormatPref = sharedPrefsResume.getString(P.KEY_PREF_time_format, "h"); 

} // [END onResume] 
+0

您是否在任何時候提交您的更改?添加它們是不夠的。 – 2013-02-13 09:28:53

+0

您是否使用PreferenceManager.setDefaultValues()加載默認值? – Clyde 2013-02-13 09:34:34

+0

@Clyde:我只是嘗試使用PreferenceManager.setDefaultValues(),但它對問題沒有影響。 – PeteH 2013-02-13 18:08:24

回答

0

我發現和解決問題。我試圖用未初始化的變量訪問SharedPrefs值(例如,P.KEY_PREF_date_format)。這就是返回默認值的原因。我現在已經將靜態變量移到了我的MainActivity中,以確保它們已被初始化。瞧。 SharePreferences現在按預期工作。

相關問題