Home > database >  Android studio : How do I retrieve specific data from Firebase?
Android studio : How do I retrieve specific data from Firebase?

Time:07-19

private TextView welcomeText;
DatabaseReference databaseReference = database.getReference("Users").child("name");

https://i.stack.imgur.com/Qayc6.png

What I want to do is retrieve the data "name" from the Firebase database and setText for the welcomeText to the data "name".

CodePudding user response:

Try this

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

    reference.child("Users").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                //model class assign
                ModelClass Class = dataSnapshot.getValue(ModelClass.class);
                String name = cartClass.getName();
            }
        }

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

        }
    });

CodePudding user response:

Hey I hope you going fantastic. Make sure you have inserted your DB URL from Firebase in your FirebaseDatabase object in your code before coding the query. So in order your project is ready you need to read the following path: DB > users > UserID > name to reach the value you are looking for. If you want to change 'name' into all of your firebase database registers you should try this.

 DatabaseReference reference = FirebaseDatabase.getInstance('FirebaseDBURL').getReference();

reference.child("Users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
            //Here you are reading all of your Users objects
            if(dataSnapshot.getKey.equals('name')){ //Here we are identifying the attr you want to change by its key name
                reference.child("Users").child(datasnapshot.getValue()).setValue(welcomeText);
            }
        }
    }

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

    }
});

I hope you solve your issue. Nevertheless if you only want to change one of your user's info you can use his/her ID directly without using for in your code and check every user in your system. reference.child("Users").child(USER_ID).setValue(welcomeText);

  • Related