2013-07-04 36 views
18

我試圖使用androids sharedpreferences,我記錄了一切,下面的代碼真的提交了字符串集。問題是,當我強制關閉應用程序並重新啓動時,settings.getStringSet返回一個空集。沒有任何錯誤消息。設置<String>在android sharedpreferences不保存強制關閉

我試過PreferenceManager.getDefaultSharedPreferences,但這對我也不起作用。

感謝您的時間。

public static final String PREFS_NAME = "MyPrefsFile"; 
private static final String FOLLOWED_ROUTES = "followedRoutes"; 

,後來被稱爲保存時:

public void onFollowClicked(View view){ 

SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); 
SharedPreferences.Editor editor = settings.edit(); 

Set<String> follows = settings.getStringSet(FOLLOWED_ROUTES, new HashSet<String>()); 
follows.add(routeId); 

editor.putStringSet(FOLLOWED_ROUTES, follows); 
editor.commit(); 

} 
+0

有什麼問題? – Blackbelt

+1

你尊重生命週期嗎?您在哪種狀態下保存數據? –

+0

在我強制退出之前每一次都保存完畢。 問題是,settings.getStringSet(...不會返回我提交給它的值 我也嘗試替換commit()apply() - 沒有成功 – Malin

回答

18

看看here

也爲REFFERENCE:

SharedPreferences

SharedPreferences.Editor

編輯:

實際上,有這一個錯誤,看到here。從那裏摘錄:

此問題在17 API級別上仍存在。

這是因爲 SharedPreferences類的getStringSet()方法不返回集合對象的副本造成的:它 返回整個對象,當你新元素添加到它,的 commitToMemory方法SharedPrefencesImpl.EditorImpl類參見 現有值等於先前存儲的值。

來解決此問題的方法是使集 通過SharedPreferences.getStringSet返回的副本或使用其他首選項隨時更改(例如,存儲的大小一個 財產強制寫入 內存每次)設置

EDIT2:

有可能是一個解決方案here,一起來看看。

+1

無法實例化類型Set ,since設置只是一個接口 – Malin

+0

只是一個問題,什麼是你的'AndroidManifest'中的minSDK? – g00dy

+0

它工作正常,如果我使用一個字符串,但不是一個stringSet,這就是我所需要的。我也試過: HashSet 下面的代碼=(HashSet )settings.getStringSet(FOLLOWED_ROUTES,new HashSet ()); – Malin

16

您也可以解決由g00dy提到這樣的錯誤:

獲取從sharedPreferences設定並保存在一個變量。

然後,只需刪除sharedpreferences中的設置,然後再保存時再次添加。

SharedPreferences.Editor editor= sharedPref.edit(); 
editor.remove("mSet"); 
editor.apply(); 
editor.putStringSet("mSet", mSet); 
editor.apply(); 

確保使用apply()或commit()兩次。

+4

這救了我的生命,希望它有更好的記錄。 –

+2

這是更好的接受解決方案 – AKTO