首页 > 解决方案 > 使用其他数据在 Firebase 中获取数据

问题描述

这是我项目的 Firebase 数据库结构。

我项目的 Firebase 数据库

我想为特定的hostelname 和 roomno获取complaint division, 。如何获取这些数据并在android项目中显示?describestat

标签: javaandroidfirebasefirebase-realtime-database

解决方案


This is a basic function in Firebase on Android. You can use ValueEventListeners with the database reference to do this. The steps to achieve the desired results can be enlisted as below:

  1. Create a Complaint model with the same fields as your database.
  2. Get the right Firebase reference for your database node and add a ValueEventListener instance to listen for database changes.
  3. Pass a DataSnapshot into the Complaint class and assign it to a Complaint object.
  4. Do what you want with the Complaint object you have obtained.

Creating a Complaint class:

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

        }
    }

Getting the data from 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();
    }
});

This is pretty much all of it. If you are still having problems, you should read a tutorial on Firebase.


推荐阅读