Android:对从SharedPreferences检索的数据进行排序

时间:2012-06-26 12:45:53

标签: android sorting sharedpreferences

我正在尝试在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
 }

修改

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

2 个答案:

答案 0 :(得分:4)

将生成的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
}

值排序 &amp;不丢失任何键值对(因为Map很容易允许重复值映射到不同的键)你需要先将它转换成 一个List并对其进行排序。

    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);
    }

答案 1 :(得分: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;
}