上面是我的 firebase 节点树。 这是我的代码:
private fun attemptAdd(){
var focus: View? = null
var cancel: Boolean = false
var prefix: String = prePrefView.text.toString() + prefText.text.toString()
var sp: SimPrefix
//checks for the length of the input
if(prefText.length()<2){
prefText.error = "invalid length"
cancel = true
focus = prefText
}
mDatabaseReference.child("simnumbers")
.orderByChild("simPref")
.equalTo(prefix)
.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {
sp = it.getValue(SimPrefix::class.java)!!
if(sp.simCard.equals(prefix)){ //checks if there is already a node with the same data
prefText.error = "already exists"
cancel = true
focus = prefText
}
}
}
override fun onCancelled(p0: DatabaseError?) {
}
})
if(cancel){
focus?.requestFocus()
}
else{ //if all is valid, proceed to the next method.
addPrefix()
}
}
我在这里假设它似乎没有进入监听器,因为它总是 继续下一个方法,允许用户输入相同的现有数据。
最佳答案
我提供了 java 代码,您可以将其更改为 kotlin,并将您的条件放入 onDatachange 方法中。
Query query1=reference.child(reference.getKey()).child("simnumbers").orderByChild("simPref").equalTo(prefix);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// here place your condition
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
关于android - 如何检查 Firebase 中的现有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50128421/