Home » Android » Firebase iteration while retrieving data android

Firebase iteration while retrieving data android

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have this Firebase database:

Student
      12312343423 (userid)
        date:10/10/1921
        name:peter
      12321321322 (userid)
        date:10/12/1924
        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(); 
                name1.setText(name);
            }}

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

Answers:

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(); 
    name1.setText(name);
  }

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

Questions:
Answers:

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() {
    @Override
    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.