繁体   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