android - 如何迭代所有数据 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;
}
解决方案
您有一个以上的条目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;
}
推荐阅读
- mysql - Remove array element by value in mysql json
- javascript - JavaScript:pushState 替换搜索字符串中的静态值
- c# - 奇怪形式的模板类名称 (.NET)
- laravel - Laravel 表单数据图像和文本字段验证
- algorithm - 对字符串中所有数字求和的算法
- javascript - 为什么只在回调函数中出现跨域错误?
- c# - 领域删除有效对象引发“尝试访问分离行”错误
- angular - 重新进入已经在Angular Ionic中初始化的页面时如何触发事件?
- python - Python 3.6 TYPE ERROR: missing 1 required positional argument
- javascript - 代码将自身循环三次,并运行两次“If”语句和一次“Else”语句