Home » Android » Firebase iteration while retrieving data android

Firebase iteration while retrieving data android

Posted by: admin November 1, 2017 Leave a comment


I have this Firebase database:

      12312343423 (userid)
      12321321322 (userid)
        name: john

Now to retrieve the data I’m using this code:

      public void onDataChange(DataSnapshot dataSnapshot) { 
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                String name=data.child("name").getValue().toString(); 

The problem with this is that the for loop:

for (DataSnapshot data : dataSnapshot.getChildren())

It is iterating through all the children, so if I have 100 students, it will pass through all those users which will take time to load. How can I let it pass through the logged in user only?(this code is in an activity after log in).


If you just want to load the data for the current user, that is a lot simpler:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Student");
String uid = FirebaseAuthentication.getInstance().getCurrentUser().getUid();
ref.child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
  public void onDataChange(DataSnapshot dataSnapshot) { 
    String name=dataSnapshot.child("name").getValue().toString(); 

The loop inside onDataChange is no longer needed here, since you’re directly accessing the node of the current user.


I am assuming that you have a Custom class with all the getter setter method of all variables used in the database.

DatabaseReference mDatabaseReference;
FirebaseUser firebaseUser;
private FirebaseAuth mAuth;

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Student");

mAuth = new FirebaseAuth.AuthStateListener() {
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        firebaseUser = firebaseAuth.getCurrentUser();
        if (firebaseUser != null) {
            // User is signed in, do all actions you need to perform.
              String name = user.getDisplayName();
              String date = user.getDate();
        } else {
            // User is not signed in, prompt to login again.

You can get the full detail and guidelines of entire project on Git Here.
For more information read the Firebase Android Authentication guide Here.