2013-03-09 30 views
1

即時通訊使用MultiSelectListPreference和值保存在陣列上..閱讀數組共享首選

如何讀取?

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); 
    Set<String> a = pref.getStringSet("tabs", null); 

    for (int i = 0; i < a.size(); i++) { 
     Log.d("salida", a[i]); 
    } 

我得到這個錯誤:類型的表達式必須是一個數組類型,但它解決了設置

+0

方括號表示法只適用於數組 – nicopico 2013-03-09 18:21:56

+0

行的錯誤? – madlymad 2013-03-09 18:52:32

回答

3

您要使用的Set,並且因爲它不是一個數組,方括號([])不能用於訪問索引。

方便地從Set讀取的值,使用增強的for循環:

for (String str: a){ 
    Log.d("salida", str); 
} 

如果你想通過刪除從該設置項爲你循環,你將不得不使用一個Iterator,如圖所示在this的答案。

或者,如果你想要的陣列,可以使用Set#toArray()

String [] prefStrings = a.toArray(new String[a.size()]); 

然後可以使用方括號(prefStrings[position])來訪問的索引。