简体   繁体   中英

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

I am trying to copy the key/value pair data from my shared preference to an ArrayList then display them on a ListView, but I am getting this error "Incompatible type" when I am using HashMap:

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();

    }

Try something like this:

    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();
    }

But I'm still not sure what do you want to achieve - because first you get all values from shared preferences, then you iterate on it, and in that loop you again put these values to shared preferences: editor.putString(entry.getKey(), entry.getValue()); editor.commit(); editor.putString(entry.getKey(), entry.getValue()); editor.commit(); I think that above lines aren't necessary.

And last one thing - you have to be sure that all values you keep in shared preferences are Strings, when you have something different then Map<String, String> map = (Map<String, String>) sharedPref.getAll(); will throw ClassCastException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM