是否有可能一个数组或对象添加到共享preferences在Android有可能、数组、对象、Android

由网友(不如不见)分享简介:如果没有,是否有什么解决办法?我有有一个名字和图标指向对象的数组列表。我不希望使用一个数据库。 If not, is there any workaround? I have an array list of objects that have a name and an icon pointer. I do not...

如果没有,是否有什么解决办法?我有有一个名字和图标指向对象的数组列表。我不希望使用一个数据库。

If not, is there any workaround? I have an array list of objects that have a name and an icon pointer. I do not want to use a database.

推荐答案

所以从Android开发者网站上的数据存储:

So from the android developer site on Data Storage:

用户preferences

User Preferences

共享preferences 没有严格的节约用户preferences,如什么铃声用户选择。如果你有兴趣为你的应用程序中创建用户preferences,见preferenceActivity,它提供了一个活动的框架,为您创建用户preferences,它会自动地坚持(使用共享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<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或更高版本,有一个method写一个字符串集

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

阅读全文

相关推荐

最新文章