Reputation: 185
I'm creating checkboxes dynamically by records in the database. I can successfully generate checkboxech for each record in database.
Than after I click on button, I want to add a record in different table based of checked checkboxes. I need to go throuht all checkboxes, see if it's checked and if YES, I need to pass the id to id_participant to create the record. But I'm lost how to do it.
Can you help please?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myDB = new DBAdapter(getContext());
final View root = inflater.inflate(R.layout.fragment_add_from_db, container, false);
final LinearLayout layout = root.findViewById(R.id.check_add_layout);
btn_ad_group = root.findViewById(R.id.btn_add_group);
Bundle bundle = getArguments();
if (bundle != null) {
id_eventu = bundle.getLong("idevent");
}
myDB.open();
pocet = myDB.getParticipantsCount();
Cursor cursor = myDB.getAllRowsParticipant();
cursor.moveToFirst();
for(int i = 0; i < pocet; i++) {
CheckBox cb = new CheckBox(root.getContext());
String name = cursor.getString(cursor.getColumnIndex("name"));
String surname = cursor.getString(cursor.getColumnIndex("surname"));
String text = name + " " + surname;
cb.setText(text);
cb.setHeight(90);
cb.setId(cursor.getInt(cursor.getColumnIndex("_id")));
layout.addView(cb);
cursor.moveToNext();
}
myDB.close();
btn_ad_group.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myDB.open();
// here I want to write into database by selected checkboxes
// I want to read id of checked checkbox and pass it to id_participant
myDB.insertRowRegistr(id_eventu, id_participant);
myDB.close();
}
});
return root;
}
Upvotes: 0
Views: 44
Reputation: 168
You've not given a lot of information, so I'll assume a couple of things.
If that LinearLayout "layout" is the parent of the checkboxes, you should be able to access its children through two functions:
int numChildren = layout.getChildCount();
for(int i=0;i<numChildren;i++){
//create a temporary checkbox variable
//make it equal to layout.getChildAt(i);
//if temp is checked, add it to a list or hand it straight to database
Should work. Never used checkboxes or databases from within android, but that should let you access each checkbox and check if it is clicked.
UPDATE
this code works as I needed. Thanks for help!
btn_ad_group.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myDB.open();
int numChildren = layout.getChildCount();
for(int i=0;i<numChildren;i++){
CheckBox temp;
temp = (CheckBox) layout.getChildAt(i);
if (temp.isChecked()) {
id_participant = (long) temp.getId();
myDB.insertRowRegistr(id_eventu, id_participant);
}
}
myDB.close();
fm.popBackStackImmediate();
}
});
Upvotes: 1