Firebase Android Database Query (Read Data)

Viewed 46

I am trying to fetch the data from the firebase database where the valueNum is the contact number with +91. I have shown the same in the screenshot attached but when I am running the code. It gave me a list of all the users even from different valueNum. However, If I pass the incorrect value, giving me the same result i.e. no error.database screen capture

private void funcDatabaseActivity(String valueNum) {
    databaseReference.child("users").child("registered-user/" + valueNum).addChildEventListener
            (new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                    if (dataSnapshot.exists()) {
                        UserData data = dataSnapshot.getValue(UserData.class);
                        Toast.makeText(ContactsActivity.this, "Data Exists - " + data.getDisplayName(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ContactsActivity.this, "Data Not Exists", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
}
1 Answers

As shown in the screenshot of the database, you are performing an incorrect sequence. I have modified this for you in the answer.

You must take a logical path to access specific information. Also, you can read about ChildEventListener, its uses, and the difference between it and addValueEventListener.

  private void funcDatabaseActivity(String valueNum) {
        databaseReference= FirebaseDatabase.getInstance().getReference("database-find-me");

        databaseReference.child("users").child("registered-user").child(valueNum).addValueEventListener(new ValueEventListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {  

             //Type here as you like

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(this, "check your internet", Toast.LENGTH_SHORT).show();
            }
        });
    }
Related