2012-06-13 41 views
1

在我的Android應用程序,我用這行代碼:爲什麼sharedpreferences的getStringSet方法不起作用?

SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE); 
Set<String> set = myPrefs.getStringSet("list", new HashSet<String>()); 

但我得到以下錯誤:

The method getStringSet(String, HashSet) is undefined for the type SharedPreferences

爲什麼會出現這個錯誤?提前致謝。

回答

2

getStringSet()在API級別增加11.您的構建目標(例如,項目>屬性> Android設備)被設定爲比API級別低的東西,請11只使用方法如果您將minSdkVersion設置爲11或更高。

+0

我正在檢查我的應用程序在HTC的野火,它有Android平臺2.2。及其使用的API級別8.我可以將我的API級別更改爲15並使用Android平臺2.2嗎?或者我必須選擇平臺4.0.3? – Piscean

+0

@Piscean:無論您如何構建應用,您的Android 2.2設備上都不存在'getStringSet()'。 – CommonsWare

+0

@Piscean如果你想使用,我已經爲你做了一個可能的解決方案。 –

1

以下是一種支持舊版本Android並處理新API的方法。它甚至可能是更有效的(店少字節):

public static void putStringCollection(final Context context,final int prefKeyResId,final Collection<String> newValue) 
    { 
    final Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit(); 
    final String key=context.getString(prefKeyResId); 
    if(newValue==null) 
     editor.remove(key).apply(); 
    else editor.putString(key,new JSONArray(newValue).toString()).apply(); 
    } 

    public static Set<String> getStringSet(final Context context,final int prefKeyResId) 
    { 
    final String key=context.getString(prefKeyResId); 
    final String str=PreferenceManager.getDefaultSharedPreferences(context).getString(key,null); 
    if(str==null) 
     return null; 
    try 
     { 
     final JSONArray jsonArray=new JSONArray(str); 
     final Set<String> result=new HashSet<>(); 
     for(int i=0;i<jsonArray.length();++i) 
     result.add(jsonArray.getString(i)); 
     return result; 
     } 
    catch(final JSONException e) 
     { 
     e.printStackTrace(); 
     PreferenceManager.getDefaultSharedPreferences(context).edit().remove(key).apply(); 
     } 
    return null; 
    } 

注:這應該是不管用的API,因爲它並沒有真正轉換自/至Android的保存數據的新方式。

+0

調用'apply()'需要API 9.我得到'調用需要API級別9(當前最小值爲8):android.content.SharedPreferences.Editor#apply'。我會用'commit()'替換它,但我被告知我們不應該從UI線程調用'commit()',因爲它同步工作(而'apply()'是異步的)。我該怎麼辦? – Solace

+0

我有一個XML字符串數組資源,我在我的Activity中檢索它,並使用它的值來填充一個'HashSet'。現在我想把這個HashSet放入SharedPreferences中。如何讓'prefKeyResId'傳遞給這些方法? – Solace

+0

您確定無法將minSdk設置爲9嗎?查看使用Android版本的人的統計信息:http://developer.android.com/about/dashboards/index.html。只有0.1%有API 8 ...無論如何,如果要放的數據不是太大,可以使用commit()。 –

相關問題