I have a checklist and I want to send all the checked items from the list to a Firebase database. I have it sending to the database but there is one problem. If the item is selected, deselected and selected again, the value will be sent twice to the database.
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i,
long l)
{
String selectedItem = ((TextView) view).getText().toString();
selectedItems.add(selectedItem);
if (unselectedItems.contains(selectedItem)) {
unselectedItems.remove(selectedItem);
}
}
});
public void showSelectedItems(View view) {
FirebaseUser user = mAuth.getCurrentUser();
String presentStudents = "";
for (int i = 0; i < selectedItems.size(); i++) {
dbPresentRef.child(selectedItems.get(i)).push().setValue("Present");
presentStudents += "-" + selectedItems.get(i) + "\n";
}
}
Just add an if
condition before adding selectedItem
ti your selectedItems
list like this.
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i,
long l)
{
String selectedItem = ((TextView) view).getText().toString();
if(!selectedItems.contains(selectedItem)){
selectedItems.add(selectedItem);
}
if (unselectedItems.contains(selectedItem)) {
unselectedItems.remove(selectedItem);
}
}
});
public void showSelectedItems(View view) {
FirebaseUser user = mAuth.getCurrentUser();
String presentStudents = "";
for (int i = 0; i < selectedItems.size(); i++) {
dbPresentRef.child(selectedItems.get(i)).push().setValue("Present");
presentStudents += "-" + selectedItems.get(i) + "\n";
}
}