我有两张桌子。 tblsubject和tbltopics。我想列出所有科目,每个科目都有主题数量。
getSubject()
public Cursor getAllSubject() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
countTopics()
public int countTopics(long subjectid) {
String where = KEY_TOPICSUBJECTID + " = " + subjectid;
Cursor c = db.query(true, DATABASE_TABLE2, ALL_KEYS2,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c.getCount();
}
viewList()这是我填充listview的地方
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void viewList() {
Cursor cursor = myDb.getAllSubject();
String[] fromFieldNames = new String[]{DBAdapter.KEY_SUBJECTID, DBAdapter.KEY_SUBJECT, DBAdapter.KEY_DATESUBJECT};
int[] toViewIds = new int[]{R.id.txtViewSubjectId, R.id.txtViewSubject, R.id.txtSubjectDateCreated};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.activity_view_the_list, cursor, fromFieldNames, toViewIds, 0);
ListView myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(myCursorAdapter);
}
我的问题是如何添加每个主题的主题数量。我可以显示主题。谢谢。
答案 0 :(得分:1)
您可以使用子查询更新主题SQL语句,以从数据库返回主题计数。见https://robots.thoughtbot.com/back-to-basics-sql#sub-queries
另外,我建议您使用自己的自定义AsyncTask和ArrayAdapter。
http://developer.android.com/guide/topics/ui/layout/listview.html
这将使您的UI更具响应性,并允许您自定义数据访问和呈现。
通过使用自定义适配器,您可以覆盖getView函数来控制结果并执行其他提取。例如,延迟将图像加载到列表视图显示中。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.subjectitem, null);
}
if (position % 2 == 1) {
v.setBackgroundColor(Color.rgb(234, 234, 234));
} else {
v.setBackgroundColor(Color.WHITE);
}
YOURDATAOBJECT p = itemList.get(position);
TextView name = (TextView) v.findViewById(R.id.name);
TextView topcount = (TextView) v.findViewById(R.id.topcount);
//You can run our additional data fetches here and update the UI
答案 1 :(得分:1)
您可以从表中使用UNION运行直接原始sql。像这样:
String select = "Select * FROM table1 UNION Select * FROM table2";
Cursor c = return db.rawQuery(select, new String[]{});