首页 > 解决方案 > 如何迭代所有数据 SQLite 并完全分配给 Hashmap?

问题描述

在我的 SQLite 中实际上有 375 个数据,但是当我尝试迭代该数据并分配给 hashmap 时,仅成功分配了 226 个数据,下面的代码有什么问题?

public static HashMap<String, String> getLanguage() {
    HashMap<String,String> hashMap = new HashMap<>();
    Cursor cursor = database.query(DB_TABLE
            , null
            , null
            , null
            , null
            , null, _ID + " ASC"
            , null);
    //cursor.moveToFirst();
    System.out.println("Cursor count"+cursor.getCount());
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        hashMap.put(cursor.getString(cursor.getColumnIndex(KEY_LANG)), cursor.getString(cursor.getColumnIndex(STRING)));
    }
    return hashMap;
}

标签: androidsqlitehashmap

解决方案


您有一个以上的条目KEY_LANG。您可以在地图值中存储列表STRING而不是一个STRING

public static HashMap<String, ArrayList<String>> getLanguage() {
    HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
    Cursor cursor = database.query(DB_TABLE,
            null,
            null,
            null,
            null,
            null,
            _ID + " ASC",
            null);
    //cursor.moveToFirst();
    System.out.println("Cursor count" + cursor.getCount());
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        String key = cursor.getString(cursor.getColumnIndex(KEY_LANG));
        String value = cursor.getString(cursor.getColumnIndex(STRING));
        if (hashMap.containsKey(key)) {
            hashMap.get(key).add(value);
        } else {
            ArrayList<String> list = new ArrayList<>();
            list.add(value);
            hashMap.put(key, list);
        }
    }
    return hashMap;
}

推荐阅读