我有两个通过密钥连接的数据库:
Questions
-------------------
_id text
1 Question 1
2 Questions 2
Answers
-------------------
_id text answered question_id
1 Yes 200 1
2 No 100 1
3 Yes 30 2
4 No 260 2
我可以使用SimpleCursorAdapter完美地调用数据。但是,我想将所有问题和答案放在列表视图中,其中一个列表项看起来像这样:
Question 1
Yes: 200
No: 100
____________
Question 2
Yes: 30
No: 260
____________
我该怎么做?我所做的最好的是:
Question 1
Yes: 200
____________
Question 1
No: 100
____________
Question 2
Yes: 30
____________
Question 2
No: 230
知道怎么做吗?我是否需要两个游标(一个用于遍历问题db,然后另一个用第一个游标中的question_id循环回答)或者我可以用一个游标实现这个吗?我还考虑过使用TableLayout进行操作,但未能正确插入行。
我希望有人能给我一些建议。
答案 0 :(得分:0)
您可以参考此代码,
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private Cursor mCursor;
// State of the row that needs to show separator
private static final int SECTIONED_STATE = 1;
// State of the row that need not show separator
private static final int REGULAR_STATE = 2;
// Cache row states based on positions
private int[] mRowStates;
public CustomAdapter(Context context, Cursor cursor) {
mContext = context;
mCursor = cursor;
mRowStates = new int[getCount()];
}
@Override
public int getCount() {
return mCursor.getCount();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
boolean showSeparator = false;
mCursor.moveToPosition(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.contact_item, null);
}
else {
view = convertView;
}
// Set contact name and number
TextView contactNameView = (TextView) view.findViewById(R.id.contact_name);
TextView phoneNumberView = (TextView) view.findViewById(R.id.phone_number);
String name = mCursor.getString( mCursor.getColumnIndex(mProjection[0]) );
String number = mCursor.getString( mCursor.getColumnIndex(mProjection[1]) );
contactNameView.setText( name );
phoneNumberView.setText( number );
// Show separator ?
switch (mRowStates[position]) {
case SECTIONED_STATE:
showSeparator = true;
break;
case REGULAR_STATE:
showSeparator = false;
break;
default:
if (position == 0) {
showSeparator = true;
}
else {
mCursor.moveToPosition(position - 1);
String previousName = mCursor.getString(mCursor.getColumnIndex(mProjection[0]));
char[] previousNameArray = previousName.toCharArray();
char[] nameArray = name.toCharArray();
if (nameArray[0] != previousNameArray[0]) {
showSeparator = true;
}
mCursor.moveToPosition(position);
}
// Cache it
mRowStates[position] = showSeparator ? SECTIONED_STATE : REGULAR_STATE;
break;
}
TextView separatorView = (TextView) view.findViewById(R.id.separator);
if (showSeparator) {
separatorView.setText(name.toCharArray(), 0, 1);
separatorView.setVisibility(View.VISIBLE);
}
else {
view.findViewById(R.id.separator).setVisibility(View.GONE);
}
return view;
}
}