当使用Android检查某行的复选框时,尝试获取第一列的值时出现问题。这是我的代码:
private ArrayList<String> exerciseIDList = new ArrayList<String>();
private void BuildTable() {
try {
String sql = "SELECT * FROM exercise";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur.getCount() != 0) {
if (mCur.moveToFirst()) {
do {
int cols = mCur.getColumnCount();
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
for (int j = 0; j < cols + 1; j++) {
if (j == cols) {
CheckBox cb = new CheckBox(this);
cb.setLayoutParams(new TableRow.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
cb.setGravity(Gravity.LEFT);
row.addView(cb);
final View rowIndex = table_layout.getChildAt(j);
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int rowID = table_layout.indexOfChild(rowIndex);
exerciseIDList.add(Integer.toString(rowID));
}
});
break;
}
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.LEFT);
tv.setTextSize(10);
tv.setText(mCur.getString(j));
row.addView(tv);
}
table_layout.addView(row);
} while (mCur.moveToNext());
}
}
} catch (SQLException mSQLException) {
throw mSQLException;
}
}
基本上我的数据库中有3列,ID,exerciseType和amount。当我执行for循环时,我将cols +1添加到每行末尾的复选框。当选中该复选框时,我应该获取第一列的值,该值是ID并存储到列表中。
但是,根据我上面提供的代码,它不会获得已检查行的第一列的值。它只是简单地从0开始循环。
任何指南?
答案 0 :(得分:1)
您遇到的问题是您指的是匿名类(View.OnClickListener())中的非final变量。有关详细信息,请参阅this post。我建议如下:
final int k = mCur.getInt(mCur.getColumnIndex("id")); //I'm not sure what you named your ID column, but put that here
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
exerciseIDList.add(Integer.toString(k));
}
});
基本上,只需创建一个新的最终变量k并将其分配给Cursor.getInt()返回。这应该可以解决你的错误。