2017-01-31 40 views
-3

我想在共享首選項中存儲多個整數值。這可能嗎?如何使用SharedPreferences保存多個Integer值?

+0

是的,你可以在SP在ArrayList和商店的ArrayList添加int類型。 – Piyush

+0

http://stackoverflow.com/questions/9054193/how-to-use-sharedpreferences-to-save-more-than-one-values – rafsanahmad007

+0

可能的重複[如何使用SharedPreferences保存多個值?](http://stackoverflow.com/questions/9054193/how-to-use-sharedpreferences-to-save-more-than-one-values) –

回答

0

對於SharedPreferences節省:

public void putListInt(String key, ArrayList<Integer> intList) { 
    checkForNullKey(key); 
    Integer[] myIntList = intList.toArray(new Integer[intList.size()]); 
    preferences.edit().putString(key, TextUtils.join("‚‗‚", myIntList)).apply(); 
} 

對於來自SharedPreferences檢索:

public ArrayList<Integer> getListInt(String key) { 
    String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚"); 
    ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList)); 
    ArrayList<Integer> newList = new ArrayList<Integer>(); 

    for (String item : arrayToList) 
     newList.add(Integer.parseInt(item)); 

    return newList; 
} 
0

您可以使用Set(表單Java集合)在共享首選項中存儲多個Integer值。

+0

有沒有方法putintSet(「key」,set); 不適合我。我不明白程序員的邏輯,因爲鋸齒甘達姆呃jawab channa hota hy。 –

0

使用Gson在SharedPreferences中存儲數組

用於存儲值。

int[] list = new int[10]; 
String string=new Gson().toJson(list); 
prefs.edit().putString("data", string).apply(); 

用於獲取價值。

String data=prefs.getString("data",null); 
int [] list=new Gson().fromJson(data,int[].class); 
相關問題