I am trying to getId in the if Statement to check whether the checkboxes are set or not but I dont know how can I define the cb
in the if Statement to get it to work.
When I declare the cb
as local variable as commeted I am getting two Errors:
The final local variable cb may already have been assigned
Cannot invoke isChecked() on the primitive type int
private void createCheckboxList(final ArrayList<Integer> items) {
final CheckBox cb;
final LinearLayout ll = (LinearLayout) findViewById(R.id.lila);
for (int i = 0; i < items.size(); i++) {
//here I am getting `The final local variable cb may already have been assigned`
cb = new CheckBox(this);
cb.setText(String.valueOf(items.get(i)));
cb.setId(i);
ll.addView(cb);
}
Button btn = new Button(this);
btn.setLayoutParams(new LinearLayout.LayoutParams(500, 150));
btn.setText("submit");
ll.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i : items) {
// here I am getting `Cannot invoke isChecked() on the primitive type int
`
if (cb.getId().isChecked()) {
}
}
}
});
}
You've declared the variable as final (can't be changed once set):
final CheckBox cb;
You would either need to set the value at that point, or remove the final modifier (your loop will try to assign a value more than once).
As for the other issue:
if (cb.getId().isChecked())
When you add .isChecked()
after .getId()
it's a short way of saying, "call this method on the returned object of the first method.
The error is telling you that method doesn't return an object, but a primitive type (int). You need to call the second method on a Checkbox object, try something like:
((CheckBox)v).isChecked();
Or, if you already have the ID:
((CheckBox) findViewById(id)).isChecked();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.