You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完整遍历SQLite数据并赋值到HashMap?及数据丢失排查

问题排查:SQLite数据遍历不全,HashMap仅存入部分数据

Hey there, let's break down why your HashMap is only capturing 226 out of 375 SQLite entries, and fix the code to ensure full data traversal.

核心原因:HashMap的键唯一性特性

First off, the most likely culprit here is duplicate values in your KEY_LANG column. HashMap enforces unique keys—every time you call put() with an existing key, it overwrites the old value with the new one. Since your cursor.getCount() returns 375, the cursor is correctly fetching all rows from the database, but duplicate keys are causing entries to be lost during the HashMap insertion.

To confirm this, run a quick SQLite query to check how many distinct KEY_LANG values exist:

SELECT COUNT(DISTINCT your_key_lang_column_name) FROM your_db_table_name;

If the result is 226, that confirms duplicate keys are the issue.

代码里的其他小问题(非直接原因,但值得修复)

Your loop logic works, but there's a more readable and robust way to iterate through the Cursor. Also, you're not closing the Cursor—this leads to database resource leaks, which can cause issues down the line.

完整遍历的修复方案

Depending on whether KEY_LANG should be unique or not, here are two solutions:

1. If KEY_LANG is supposed to be unique

First, fix your database data to eliminate duplicate KEY_LANG values (e.g., add a unique constraint on the column, or clean up existing duplicates). Then, use this cleaned-up code with proper Cursor handling:

public static HashMap<String, String> getLanguage() {
    HashMap<String, String> hashMap = new HashMap<>();
    // Use try-with-resources to auto-close the Cursor (Java 7+)
    try (Cursor cursor = database.query(DB_TABLE, null, null, null, null, null, _ID + " ASC", null)) {
        System.out.println("Cursor count: " + cursor.getCount());
        
        if (cursor.moveToFirst()) {
            do {
                String langKey = cursor.getString(cursor.getColumnIndex(KEY_LANG));
                String langValue = cursor.getString(cursor.getColumnIndex(STRING));
                hashMap.put(langKey, langValue);
            } while (cursor.moveToNext());
        }
    }
    return hashMap;
}

2. If KEY_LANG allows duplicates (need to keep all entries)

Since HashMap can't store multiple values for the same key, switch to a HashMap<String, List<String>> to group values by their KEY_LANG:

public static HashMap<String, List<String>> getLanguage() {
    HashMap<String, List<String>> langMap = new HashMap<>();
    try (Cursor cursor = database.query(DB_TABLE, null, null, null, null, null, _ID + " ASC", null)) {
        System.out.println("Cursor count: " + cursor.getCount());
        
        if (cursor.moveToFirst()) {
            do {
                String langKey = cursor.getString(cursor.getColumnIndex(KEY_LANG));
                String langValue = cursor.getString(cursor.getColumnIndex(STRING));
                
                // Add value to existing list or create a new list
                langMap.computeIfAbsent(langKey, k -> new ArrayList<>()).add(langValue);
            } while (cursor.moveToNext());
        }
    }
    return langMap;
}

The computeIfAbsent method simplifies checking for existing keys and creating new lists when needed.

Final Notes

  • Always close your Cursor (try-with-resources is the safest way in modern Java)
  • Verify your database schema and data to ensure keys behave as expected
  • If you need to preserve all rows, use a collection that supports multiple values per key (like the list-backed HashMap above)

内容的提问来源于stack exchange,提问作者asqa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:35:06