簡體   English   中英

如何將共享的首選項數據保存到ArrayList中,然后顯示在ListView上?

[英]How to save shared preference data into an ArrayList then display on a ListView?

我試圖將鍵/值對數據從共享的首選項復制到ArrayList,然后在ListView上顯示它們,但是在使用HashMap時出現此錯誤“ Incompatible type”:

SharedPreferences sharedPref = getSharedPreferences("STData",  Context.MODE_PRIVATE);
//to edit the data or add data inside my file "STData"
SharedPreferences.Editor editor = sharedPref.edit();

//create an Arraylist to store values from the sharedPref Object
ArrayList<String> STArrayList = new ArrayList<String>();

for (HashMap<String, String> map : STArrayList)

    for (Map.Entry<String, String> entry : map.entrySet())
    {
        editor.putString(entry.getKey(), entry.getValue());
        editor.commit();

        String savedPref = sharedPref.getString(entry.getKey(), "");
        STArrayList.add(savedPref);
        Toast.makeText(getApplicationContext(),savedPref, Toast.LENGTH_LONG).show();

    }

嘗試這樣的事情:

    SharedPreferences sharedPref = getSharedPreferences("STData", Context.MODE_PRIVATE);
    //to edit the data or add data inside my file "STData"
    SharedPreferences.Editor editor = sharedPref.edit();

    //create an Arraylist to store values from the sharedPref Object
    ArrayList<String> STArrayList = new ArrayList<String>();
    Map<String, String> map = (Map<String, String>) sharedPref.getAll();

    for (Map.Entry<String, String> entry : map.entrySet()) {
        editor.putString(entry.getKey(), entry.getValue());
        editor.commit();

        String savedPref = sharedPref.getString(entry.getKey(), "");
        STArrayList.add(savedPref);
        Toast.makeText(getApplicationContext(), savedPref, Toast.LENGTH_LONG).show();
    }

但是我仍然不確定要實現什么目標-因為首先從共享首選項中獲取所有值,然后對其進行迭代,然后在該循​​環中再次將這些值放入共享首選項中: editor.putString(entry.getKey(), entry.getValue()); editor.commit(); editor.putString(entry.getKey(), entry.getValue()); editor.commit(); 我認為上述行是不必要的。

最后一件事-您必須確保在共享首選項中保留的所有值都是字符串,如果您有其他不同,則Map<String, String> map = (Map<String, String>) sharedPref.getAll(); 將拋出ClassCastException。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM