Is it possible to add an array or object to SharedPreferences on Android

前端 未结 11 1604
别跟我提以往
别跟我提以往 2020-11-22 11:27

I have an ArrayList of objects that have a name and an icon pointer and I want to save it in SharedPreferences. How can I do?

NOTE:

11条回答
  •  有刺的猬
    2020-11-22 12:05

    So from the android developer site on Data Storage:

    User Preferences

    Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

    So I think it is okay since it is simply just key-value pairs which are persisted.

    To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:

    // my list of names, icon locations
    Map nameIcons = new HashMap();
    nameIcons.put("Noel", "/location/to/noel/icon.png");
    nameIcons.put("Bob", "another/location/to/bob/icon.png");
    nameIcons.put("another name", "last/location/icon.png");
    
    SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
    SharedPreferences.Editor keyValuesEditor = keyValues.edit();
    
    for (String s : nameIcons.keySet()) {
        // use the name as the key, and the icon as the value
        keyValuesEditor.putString(s, nameIcons.get(s));
    }
    keyValuesEditor.commit()
    

    You would do something similar to read the key-value pairs again. Let me know if this works.

    Update: If you're using API level 11 or later, there is a method to write out a String Set

提交回复
热议问题