我对如何将两个单独的数据库查询合并到一个 listView 中感到很困惑。
目前,我的 listView 由以下适配器填充,它查询数据库中损坏的组件表并提供特定位置的损坏组件列表:
private class MyListAdapter extends ResourceCursorAdapter {
// In your ListActivity class, create a new inner class that extends ResourceCursorAdapter.
//This inner class is the custom CursorAdapter we will use to manage how data is bound to a list item:
public MyListAdapter(Context context, Cursor cursor) {
super(context, R.layout.row_location, cursor);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView text_first_line = (TextView) view.findViewById(R.id.location_row_item_main_text);
TextView text_second_line = (TextView) view.findViewById(R.id.location_row_item_secondary_text);
ImageView flagIcon = (ImageView) view.findViewById(R.id.flagIcon);
String row_text_component = cursor.getString(cursor.getColumnIndex(RMDbAdapter.COMPONENT));
String row_text_position = ", Position " + cursor.getString(cursor.getColumnIndex(RMDbAdapter.POSITION));
if(row_text_position.equals(", Position Not Applicable")){
row_text_position = "";
}
String row_text_action = " - " + cursor.getString(cursor.getColumnIndex(RMDbAdapter.ACTION_REQUIRED));
text_first_line.setText(row_text_component + row_text_position + row_text_action);
text_second_line.setText("Dexion Speedlock, S Duty, 3000mm");
String risk = cursor.getString(cursor.getColumnIndex(RMDbAdapter.RISK));
if (risk.equals("Red Risk")){
flagIcon.setImageResource(R.drawable.red_flag);
}
else if (risk.equals("Green Risk")){
flagIcon.setImageResource(R.drawable.green_flag);
}
else if (risk.equals("No Risk")){
flagIcon.setImageResource(R.drawable.note);
}
}
}
当我在 Activity 开始时调用以下内容时触发:
private void setAdapter(){
// Get a Cursor for the list items
Cursor listComponentCursor = rmDbHelper.fetchDamagedComponentsForLocation(locationId);
componentCursorSize = listComponentCursor.getCount();
startManagingCursor(listComponentCursor);
// set the custom list adapter
setListAdapter(new MyListAdapter(this, listComponentCursor));
}
所以我还想在一个单独的表(这次是问题表)上创建第二个查询,并将其添加到损坏组件列表下的 listView 中。
阅读此 Listview from multiple tables? ,我认为我应该使用 Join 或 Merge 游标。但是,根据我的研究,我仍然不知道如何将这两个概念集成到我的代码中。
谁能指出我正确的方向?
最佳答案
虽然您没有显示它,但我假设您覆盖了游标适配器的 newView
方法。 MergeCursor 只会将一个查询的结果堆叠在下一个查询之上。 CursorJoiner 几乎可以将结果并排放置。听起来您想要一个 MergeCursor。
如果您只想将第二个查询的结果连接到第一个查询,请执行两个查询并创建一个 MergeCursor。如果您需要它们具有不同的布局,或者它们具有不同的列名,则需要重写适配器中的 getItemViewType
方法。然后,在您的 newView
方法中,您可以根据类型填充不同的 View 。在 bindView
中,您需要检查类型并将正确的值应用于正确的 View 。
关于您的代码的一些随机提示:
1) 使用 ViewHolder 模式,速度更快。
2) 用 "literal string".equals(variable)
代替 variable.equals("literal string")
总是更好,因为文字字符串不能抛出空指针异常
关于android - 如何将两个数据库表中的数据合并到一个 listView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13057462/