Bundle bundle = getIntent().getExtras();
String name = bundle.getString("name");
mValueView = (TextView) findViewById(R.id.textView);
mRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/Users");
com.google.firebase.database.Query query = mRef.child("Users").orderByChild("title").equalTo(name);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Map<String,Object> map = (Map<String, Object>) dataSnapshot.getValue();
//String Title = (String) map.get("title");
String Title = dataSnapshot.child("title").getValue().toString();
mValueView.setText(Title);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我想显示对象标题是同名值。
这是Firebase数据库:
答案 0 :(得分:1)
如果您只想搜索一次标题值而不收听更新,只需使用:
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}});
然后,如果您获得对“用户”的引用。你可以用迭代做一些逻辑,例如:
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
String title = (String) singleSnapshot.child("title").getValue();
//do your logic
}
答案 1 :(得分:1)
您的代码中存在两个问题:
Users
onDataChange
无法处理Users
两次mRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/Users");
// ^^^^^
Query query = mRef.child("Users").orderByChild("title").equalTo(name);
// ^^^^^
轻松修复:
mRef = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/");
Query query = mRef.child("Users").orderByChild("title").equalTo(name);
我不确定你为什么开始使用getReferenceFromUrl()
。对于大多数应用程序来说,这样做更简单:
mRef = FirebaseDatabase.getInstance().getReference();
对Firebase数据库执行查询时,可能会有多个结果。因此快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
System.out.println(snapshot.getKey());
System.out.println(snapshot.child("title").getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});