是否可以将数组或对象添加到 Android 上的 SharedPreferences [英] Is it possible to add an array or object to SharedPreferences on Android

查看:27
本文介绍了是否可以将数组或对象添加到 Android 上的 SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList 对象,它们有一个名称和一个图标指针,我想将它保存在 SharedPreferences 中.我该怎么办?

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?

注意:我不想使用数据库

推荐答案

So from the android developer site on 数据存储:

So from the android developer site on Data Storage:

用户偏好

共享首选项并非严格用于保存用户首选项",例如用户选择的铃声.如果您有兴趣为您的应用程序创建用户首选项,请参阅 PreferenceActivity,它提供了一个 Activity 框架供您创建用户首选项,该框架将自动保留(使用共享首选项).

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<String, String> nameIcons = new HashMap<String, String>();
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.

更新:如果您使用 API 级别 11 或更高版本,则有一个 方法写出一个字符串集

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

这篇关于是否可以将数组或对象添加到 Android 上的 SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆