[英]Why this android function always return false?
Im using this function for checking a specific date is present in the database or not, but I'm getting false every time and the new date is also updated in the database 我正在使用此功能检查数据库中是否存在特定日期,但是每次都会出错,并且数据库中也会更新新日期
private boolean dateCheck() {
dateKey = false;
final ProgressDialog pg = new ProgressDialog(AdminMain.this);
pg.setMessage("Validating Date");
pg.setCanceledOnTouchOutside(false);
pg.setCancelable(false);
pg.show();
final DatabaseReference dbDate = FirebaseDatabase.getInstance().getReference("Dates").child(batch).child(sem);
dbDate.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(date)) {
pg.dismiss();
Snackbar.make(findViewById(android.R.id.content), "Attendance has been already sumbitted", Snackbar.LENGTH_LONG).show();
dateKey = false;
} else {
dateKey = true;
dbDate.child(date).setValue(true);
pg.dismiss();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Snackbar.make(findViewById(android.R.id.content), databaseError.getMessage(), Snackbar.LENGTH_SHORT).show();
pg.dismiss();
dateKey=false;
}
});
return dateKey;
}
When you are returning the dateKey
boolean as a result of a method, you are always returning the value that was assigned first, which is false
. 当作为方法的结果返回
dateKey
布尔值时,总是返回首先分配的值false
。 This is happening because your if statement that exists inside onDataChange()
isn't yet triggered when you return that result and that's why is always false. 之所以发生这种情况,是因为在返回该结果时尚未触发
onDataChange()
中存在的if语句,因此始终为false。 So onDataChange()
method returns immediately after it's invoked, and the callback from the Task it returns, will be called some time later. 因此
onDataChange()
方法在调用后立即返回,并且它返回的Task中的回调将在一段时间后调用。
There are no guarantees about how long it will take. 无法保证需要多长时间。 So it may take from a few hundred milliseconds to a few seconds before that data is available.
因此,可能需要几百毫秒到几秒钟的时间才能获得该数据。 Basically, you're trying to return a value synchronously from an API that's asynchronous.
基本上,您试图从异步的API同步返回值。 That's not a good idea.
那不是一个好主意。 You should handle the APIs asynchronously as intended.
您应该按预期异步处理API。
A quick solve for this problem would be to use your boolean dateKey
only inside the onDataChange()
method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. 一个快速的解决这个问题是使用你的布尔
dateKey
只有内部onDataChange()
方法,否则我建议你看我anwser从这个最后部分职位中,我已经解释了如何可以使用自定义的回调来完成。 You can also take a look at this video for a better understanding. 您也可以观看此视频 ,以更好地理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.