1

我正在尝试在 Android 中存储数据。我正在使用SharedPreferences. 我正在使用以下方法检索这些数据:

 SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
            Map<String, ?> keys = myPrefs.getAll();
            for (Map.Entry<String, ?> entry : keys.entrySet()) {
                Log.i("map values", entry.getKey());
                            //some code
 }

编辑:

但是检索到的数据与插入的顺序不同。如何获得相同的订单?

4

2 回答 2

5

将结果复制Map到 的实现中SortedMap,例如TreeMap

像这样(按键排序):

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
for (Map.Entry<String, ?> entry : keys.entrySet()) {
    Log.i("map values", entry.getKey());
    //some code
}

要按值排序并且 不丢失任何键值对(因为 Map 很容易允许重复值映射到不同的键),您需要首先将其转换为 aList并对其进行排序。

    List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
    for (Map.Entry<String, ?> entry : keys.entrySet()) {
        Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
        sortedByValue.add(e);
    }

    // Pair doesn't have a comparator, so you're going to need to write one.
    Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
        public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {
            // This is a naive and shitty comparator, but it works for
            // arbitrary objects. Sort of. Tweak depending on the order you need.
            String sls = String.valueOf(lhs.first);
            String srs = String.valueOf(rhs.first);
            int res = sls.compareTo(srs);
            // Sort on value first, key second
            return res == 0 ? lhs.second.compareTo(rhs.second) : res;
        }
    });

    for (Pair<Object, String> pair : sortedByValue) {
        Log.i("map values", pair.first + "/" + pair.second);
    }
于 2012-06-26T12:55:32.997 回答
0

添加一个带有顺序的属性,像这样...首先保存设置...

public static void saveSettings(final Editor editor, final String [] order) {
    final String csl = toString(order);//comma separated
    editor.putString("insert_order", csl);
    for (int i = 0; i < values.length; i++) {
        editor.putString(values[i], your_value[i]);
    }
}

现在加载它们:

public static List<String> loadSetting(final SharedPreferences preferences) {
    final List<String> inOrder = new ArrayList<>(); 
    final String[] ordering = preferences.getString("insert_order", "").split(",");
    for (final String item : ordering) {
        final String value = (String) preferences.getString(item, "");
        inOrder.add(value);
    }
    return inOrder;
}
于 2014-10-03T09:39:48.753 回答