我需要在随机键中找到现有的Child,并且使用OrderByChild()和EqualTo()来过滤查询,但是它的行为太奇怪了,因为有时它显示仅一个Child存在,而有时却不存在工作。
我需要检查“ 2019年2月”的孩子(date_expense)是否存在?我已经尝试过了
MainActivity
databaseReference = firebaseDatabase.getReference("Expenses_Details");
expensesaddref = databaseReference.child(username).child("Expense_Month").child(monthyr);
int currentInt=Integer.parseInt(currentdate);
numberToWord((currentInt % 100));
Log.d("date_string",String.valueOf(dateString));
final String date_expense=expensesname +"" + dateString;
final ExpenseClass expenses=new ExpenseClass(expensesname,currentdate,date_expense,totalcost);
expensesaddref.orderByChild("date_expense").equalTo(date_expense).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getContext(), "Expense Already exists!!", Toast.LENGTH_SHORT).show();
}
else {
String key = expensesaddref.push().getKey();
expensesaddref.child(key).setValue(expenses);
showListAdd(expensesname);
Log.d("Adding", "Data Adding");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
}}
注意
如果孩子已经存在于数据库中,那么它应该显示吐司,但是即使孩子已经是db,费用也会再次增加
在程序中,
monthYr
是February_2019
Currentdate
是今天的日期
dateString
是日期(以1、11、20为单位)
答案 0 :(得分:0)
我发现下面的代码根据我的需要工作
ValueEventListener valueEventListener=new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
boolean isTitleAlreadyUsed = false;
for (DataSnapshot ds: dataSnapshot.getChildren()) {
if (ds.hasChild("date_expense") && (expDate.equals(ds.child("date_expense").getValue()))) {
isTitleAlreadyUsed = true;
}
}
if(isTitleAlreadyUsed){
Toast.makeText(getContext(),"Exist",Toast.LENGTH_SHORT).show();
}else
{
String key=expensesaddref.push().getKey();
expensesaddref.child(key).setValue(expenseClass);
showListAdd(lower_exp);
Toast.makeText(getContext(),"Added",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
expensesaddref.addListenerForSingleValueEvent(valueEventListener);