"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) {
}
});
我的问题是如何检查卡洛斯'存在?
答案 0 :(得分:1)
对于初学者来说,你的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")) {}
}
答案 1 :(得分:0)
请使用此代码:
if (snapshot.child("firstName").getValue().equals("Lovelace")) {
System.out.println("first name exists");
} else {
System.out.println("does not exist");
}
如果你有firstName的值,而不是一个,假设你使用的是map
,请使用以下代码:
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");
}
}
使用ArrayList
的另一种解决方案。这是代码:
DatabaseReference users = ref.child("name");
users.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
ArrayList<String> arrayList = new ArrayList<>();
for(DataSnapshot ds : snapshot.getChildren()) {
String lastname = ds.getValue(String.class);
arrayList.add(lastname);
}
if(arrayList.contains("Lovelace")) {
System.out.println("first name exists");
} else {
System.out.println("does not exist");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
希望它有所帮助。