java - 如何从不同的 SQLite 表中获取数据并将其显示在一个 SimpleAdapter Android 中
问题描述
我是 Android 新手,需要在 Listview 中显示 Starttime、Stoptime 和 Name。为了显示,我使用 SimpleAdapter。问题是我有两个 SQLite 表:
餐桌时间: 开始时间 | 停止时间 | 学生卡
表学生: 学生证 | 学生姓名
现在,我使用光标从我的数据库中获取开始时间、停止时间和学生 ID
Cursor curm1 = myDb.getAllMonday();
while (curm1.moveToNext()) {
final HashMap<String, String> resultMapMonday = new HashMap<>();
resultMapMonday.put("Start", curm1.getString(3));
resultMapMonday.put("Stop", curm1.getString(4));
resultMapMonday.put("Student", curm1.getString(5));
arrayListStudentsName.add(curm1.getString(5));
listItemsMo.add(resultMapMonday);
}
然后是一个 SimpleAdapter 来显示它:
final SimpleAdapter adaptersimpleMo = new SimpleAdapter(this, listItemsMo, R.layout.timeslots_configurate,
new String[]{"Start", "Stop", "Student"},
new int[]{R.id.oneTime_start, R.id.oneTime_stop, R.id.selectedStudent});
但我想显示存储在另一个表中的名称,而不是 id。我可以用另一个游标获得 Id 的匹配名称
Cursor curm2 = myDb.getNamesbyIDs(arrayListStudentsName);
while (curm2.moveToNext()) {
final HashMap<String, String> resultMapNames = new HashMap<>();
resultMapNames.put("Name", curm2.getString(1));
}
但我不知道如何让同一个适配器中的名称显示与匹配的开始和停止时间相同的列表项中的名称。
编辑
public Cursor getAllMonday() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + TABLE_TIME + " WHERE day = 'Montag' ORDER BY CAST(start as unsigned)", null);
return res;
}
解决方案
更改getAllMonday()
为使用连接 2 个表的查询:
public Cursor getAllMonday() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "SELECT t.Start, t.Stop, s.Studentname FROM " + TABLE_TIME + " AS t INNER JOIN " + TABLE_STUDENT +
" AS s ON s.StudentID = t.StudentID WHERE t.day = 'Montag' ORDER BY CAST(t.start as unsigned)"
Cursor res = db.rawQuery(sql, null);
return res;
}
将我使用的表变量TABLE_STUDENT
和列名称更改为实际名称。
现在光标包含学生的姓名而不是 id。
接下来将代码更改为:
Cursor curm1 = myDb.getAllMonday();
while (curm1.moveToNext()) {
final HashMap<String, String> resultMapMonday = new HashMap<>();
resultMapMonday.put("Start", curm1.getString(curm1.getColumnIndex("Start")));
resultMapMonday.put("Stop", curm1.getString(curm1.getColumnIndex("Stop")));
resultMapMonday.put("Student", curm1.getString(curm1.getColumnIndex("Studentname")));
arrayListStudentsName.add(curm1.getString(curm1.getColumnIndex("Studentname")));
listItemsMo.add(resultMapMonday);
}
curm1.close();
推荐阅读
- laravel - Vue.js 转换在 Laravel Blade + Sass 中不起作用
- core-ui - 添加具有默认布局的新组件
- python - 无法在 Gtk.TextView i Python 3 中对列进行排序
- javascript - 在数组中使用切片不会影响模板
- git - 如何恢复当前 git 提交的文件
- iphone - 如何使用蓝牙串行配置文件将串行数据发送到 Mac
- postgresql - 根据一个值删除重复项
- java - 使用堆的最佳优先搜索实现
- google-app-maker - Google App Maker:外部 JavaScript 库
- php - 将生成的字符串用于 MySQL 中带有变量的数组