【问题标题】:How to iterate all data SQLite and assign to Hashmap completely?如何迭代所有数据 SQLite 并完全分配给 Hashmap?
【发布时间】:2019-03-19 12:06:14
【问题描述】:

在我的 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;
}

【问题讨论】:

    标签: android sqlite hashmap


    【解决方案1】:

    您有多个条目,其中一个 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;
    }
    

    【讨论】:

    • 对不起,我不明白,你能写出正确的代码吗?
    • @asqa 检查一下
    • 感谢@shmakoca,我已经尝试过您的代码,但仍然相同,当达到 225 hashMap.put(key, list) 将不会执行并跳转返回 hashmap
    • 我已经告诉过你,你有相同语言的重复条目@asqa 检查你的数据库
    猜你喜欢
    • 2020-08-24
    • 2012-11-09
    • 1970-01-01
    • 2016-02-16
    • 2022-07-06
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多