Home > Software engineering >  Retrive firebase realtime data to android studio java app interface
Retrive firebase realtime data to android studio java app interface

Time:04-01

I need to get the specific user data using the user email on the real time database. This is my code, This code running without errors but the data is not display in the interface.I think datasnapshot retrieving part is not correct. please help me to solve this.

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String userEmail = user.getEmail();

    DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();


    Query myUsersQuery = rootReference.child("Children").orderByChild("childrenParentEmail").equalTo(userEmail);

   myUsersQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
  
                String name = dataSnapshot.child("Children").getValue(String.class);
                childrenNameEdt.setText(name);
                childrenBirthdayEdt.setText(dataSnapshot.child("childrenBirthday").getValue(String.class));
                childrenParentNameEdt.setText(dataSnapshot.child("childrenParentName").getValue(String.class));
                childrenParentAddressEdt.setText(dataSnapshot.child("childrenParentAddress").getValue(String.class));
                childrenParentContactNumberEdt.setText(dataSnapshot.child("childrenParentContactNumber").getValue(String.class));
                childrenParentEmailEdt.setText(dataSnapshot.child("childrenParentEmail").getValue(String.class));
                childrenTransportTypeEdt.setText(dataSnapshot.child("childrenTransportType").getValue(String.class));
                childrenTransportContactNumberEdt.setText(dataSnapshot.child("childrenTransportContactNumber").getValue(String.class));
                //childrenID.setText(dataSnapshot.child("password").getValue(String.class));
   
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            throw error.toException();

        }


    });

CodePudding user response:

When you execute a query against the Firebase Realtime Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your code will need to handle that list, by looping over dataSnapshot.getChildren(). So something like:

myUsersQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren();
            String name = snapshot.child("Children").getValue(String.class);
            childrenNameEdt.setText(name);
            ...
  • Related