Java 检查Firebase中是否存在值?
屏幕截图:假设数据库中有以下数据:Java 检查Firebase中是否存在值?,java,firebase,firebase-realtime-database,Java,Firebase,Firebase Realtime Database,屏幕截图:假设数据库中有以下数据: "name": { "lastName": { "Markis" "PopMal" "Carlos" } } 我们的代码是: final DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://myproj.firebaseio.com/");
"name": {
"lastName": { "Markis"
"PopMal"
"Carlos"
}
}
我们的代码是:
final DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://myproj.firebaseio.com/");
DatabaseReference users = ref.child("name");
users.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.child(lastName).exists()) {
System.out.println("last name exists");
}
else
{
System.out.println("does not exist");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我的问题是如何检查“Carlos”是否存在?请使用以下代码:
if (snapshot.child("firstName").getValue().equals("Lovelace")) {
System.out.println("first name exists");
} else {
System.out.println("does not exist");
}
Map<String, String> map = (TreeMap<String, String>) snapshot.child("firstName").getValue();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue().equals("Lovelace")) {
System.out.println("first name exists");
} else {
System.out.println("does not exist");
}
}
如果您的firstName有更多值,而不是一个值,并且假设您使用的是映射
,请使用以下代码:
if (snapshot.child("firstName").getValue().equals("Lovelace")) {
System.out.println("first name exists");
} else {
System.out.println("does not exist");
}
Map<String, String> map = (TreeMap<String, String>) snapshot.child("firstName").getValue();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue().equals("Lovelace")) {
System.out.println("first name exists");
} else {
System.out.println("does not exist");
}
}
希望能有所帮助。对于初学者来说,您的json与图像不匹配,但以下是我将尝试的
DatabaseReference users = ref.child("name");
users.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for ( DataSnapshot child : snapshot.getChildren()) {
String lastname = child.getValue(String.class);
if (lastname.equals("Carlos")) {}
}
我想检查一下“Lovelace”是否存在。如果firstName是空的就不会抱歉,我忘了一些引号。正确的是
child(“firstName”)
。看看我更新的答案。我不明白你说的“当名字有很多孩子的时候”firstName
是name
节点的第二个子节点。其他比这更简单的解决方案是不存在的。这是最简单的,使用String类中的equals()
方法对两个字符串进行比较。我的意思是,当lastName有许多子项时,它不起作用,我确信有一个简单的解决方案我不使用映射。我一直在向lastname添加值您只是在名称引用中查找snapshot.getChildren()
吗?@cricket\u 007我不理解onDataChange(DataSnapshot snapshot){
…是什么意思查找姓名下所有可能的姓氏key@cricket_007我只是想看看“卡洛斯”是否存在!仅此而已!我怎么能简单地做到这一点?:)你是否在尝试我的建议?