我有一个核对清单,我想将列表中所有选中的项目发送到Firebase数据库。我已将其发送到数据库,但有一个问题。如果选择、取消选择并再次选择该项,则该值将发送到数据库两次。
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";
}
}
只需添加一个if
条件,然后再像这样添加selectedItem
selectedItems
列表。
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";
}
}