简体   繁体   中英

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

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".

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) {

        }
    });

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM