问题描述
如果没有,是否有什么解决办法?我有有一个名字和图标指向对象的数组列表。我不希望使用一个数据库。
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
共享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或更高版本,有一个<一个href="http://developer.android.com/reference/android/content/Shared$p$pferences.Editor.html#putStringSet%28java.lang.String,%20java.util.Set%3Cjava.lang.String%3E%29">method写一个字符串集
Update: If you're using API level 11 or later, there is a method to write out a String Set
这篇关于是否有可能一个数组或对象添加到共享preferences在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!