Reputation:
I am having some problem when trying to get the value of the first column when the checkbox of certain row is checked using Android. Here is my codes:
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;
}
}
Basically I have 3 columns in my database, ID, exerciseType and amount. When I do a for loop, I +1 the cols to add checkbox to the end of each row. And when the checkbox is checked, I supposed to get the value of the first column which is ID and store into the list.
However, from the codes I provided above, it does not get the value of the first column of checked row. It is just simply looping start from 0.
Any guides?
Upvotes: 0
Views: 1151
Reputation: 101
The issue you are having is that you are referring to a non-final variable inside an anonymous class (View.OnClickListener()). See this post for more information. I would suggest the following:
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));
}
});
Basically, just create a new final variable k and assign it to your return from the Cursor.getInt(). That should get you through this error.
Upvotes: 1