这是我项目的Firebase数据库结构。
我想获取特定旅馆名称和Roomno的complaint division
,describe
,stat
。如何获取这些数据并在android项目中显示?
答案 0 :(得分:1)
这是Android Firebase中的基本功能。您可以将ValueEventListeners与数据库引用一起使用来执行此操作。 取得预期结果的步骤可列举如下:
创建投诉类:
class Complaint {
// your fields should have the same name as database fields to prevent unnecessary complications
public String complaintdivision;
public String complaintid;
public String describe;
public String hostelname;
public String roomno;
public String stat;
public Complaint(){// required for Firebase
}
}
从Firebase获取数据:
ArrayList<Complaint> myComplaintArrayList = new ArrayList<>();
FirebaseDatabase.getInstance().getReference().child("Complaints").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot complaint: dataSnapshot.getChildren()){
Complaint c = complaint.getValue(Complaint.class);
myComplaintArrayList.add(c);// you should have an ArrayList<Complaint> for this loop
}
// do what you want with the items you obtained
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
这几乎全部。如果仍然有问题,则应阅读Firebase上的教程。
答案 1 :(得分:1)
要获取所有这些值,请使用以下代码行:
element.addEventListener
您的logcat中的输出将是:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference complaintsRef = rootRef.child("Complaints");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String complaintDivision = ds.child("complaintdivision").getValue(String.class);
//Get the other properties in the same way
Log.d(TAG, complaintDivision);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
complaintsRef.addListenerForSingleValueEvent(valueEventListener);
答案 2 :(得分:0)
因此,要获取数据,您首先需要声明一个指向数据库的Firebase DatabaseReference对象:
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
然后您将使用该对象编写查询:
Query query = mDatabase.child("Complaints");
现在,您将SingleValueEventListener附加到此查询:
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Write a for-each loop to cycle through your node's children
for(DataSnapshot data: dataSnapshot.getChildren()){
//Create an instance of your model class to
//store the received data
//Make sure you have an empty constructor in your model class
Complaint complaint = data.getValue(Complaint.class);
//then simply call your getters on the complaint object
//to get what you need
complaint.getComplaintDivision();
complaint.getDescription();
//...
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
要获取更具体的信息,只需修改查询。 有关查询的更多信息,请see this