【发布时间】:2018-03-06 04:39:05
【问题描述】:
我需要在共享首选项中存储一个数组,而不使用Prefser 或Hawk 等外部库。我试过了,发现他们两个都有很多问题。
所以我的搜索让我找到了两种不同的方法:
-
使用集合:
//Set the values Set<String> set = new HashSet<String>(); set.addAll(listOfExistingScores); scoreEditor.putStringSet("key", set); scoreEditor.commit(); //Retrieve the values Set<String> set = myScores.getStringSet("key", null); -
使用字符串操作:
//Set the values StringBuilder sb = new StringBuilder(); for (int i = 0; i < playlists.length; i++) { sb.append(playlists[i]).append(","); } prefsEditor.putString(PLAYLISTS, sb.toString()); //Retrieve the values String[] playlists = playlist.split(",");
问题:当物品的顺序无关紧要并且我有大量物品(例如 > 300)时,什么是更有效的方法?
【问题讨论】:
-
你为什么不使用数据库?我通常不会对超过 30 个键使用 SharedPreferences
-
@gmetax,你是对的,通常情况下,我也是这样做的。但在这种情况下,这是我唯一需要存储的东西,我不想仅仅为一个 ArrayList 搞乱数据库实现。
-
我找不到 SharedPreferences 的限制存储,但我认为在 SharedPreferences 上存储超过 1000 个值不是一个好习惯
-
@EmilAdz,这不是一个有效的解决方案,这只是做你的事情的一种方式。即使在 SharedPreferences 中存储这么多数据也永远不会有效。
标签: android arraylist save sharedpreferences