Retrieving specific data from Firebase Database

前端 未结 2 2037
一整个雨季
一整个雨季 2021-02-09 04:16

I\'m creating a chat app on android using Firebase Database and Java. Whenever the user is first registered, it stores their username into the database under the nodes use

2条回答
  •  走了就别回头了
    2021-02-09 05:03

    You aren't getting the value properly. You need to attach a listener to you child and get updates. You do that like this:

    // Get a reference to your user
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("server/path/to/profile");
    
    // Attach a listener to read the data at your profile reference
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Profile profile = dataSnapshot.getValue(Profile.class);
            System.out.println(profile.getUsername());
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());
        }
    });
    

    You can find more information and examples on the Firebase website. Keep in mind that you don't make requests to get data from Firebase. You attach listeners to the children and then get the data from the listener. This example assumes that you have a Profile model, with a method to get the username. This would return your Profile object and would enable you to get whatever data you need off of that object.

提交回复
热议问题