0

I have the following code implemented in my project:

DatabaseReference online = mPostReference.child("online").child(msg.friend_id);
online.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Online post = dataSnapshot.getValue(Online.class);
        if ( viewHolder.getDiff(post.timestamp) < 1){
            viewHolder.setOnline("visible");
        } else {
            viewHolder.setOnline("gone");
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});

I have 2 items inside the recyclerview and both items have the listener attached. When data changes inside the database, the first item will return true and will show the state as online, but even the second item will be false, the icon will appear on the second item as well unless I refresh the activity by closing and reopening the app.. What I am missing here? Do I need to notify my adapter? I don't think both items goes through the if and else statements

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
AlwaysConfused
  • 729
  • 2
  • 12
  • 37

1 Answers1

0

This is happening because onDataChange is called asynchronously. This means that setOnline() method is executed before onDataChange has been called. That's why that method is executed after you reopen your activity. The if statement works correctly. So in order to solve this, please visit this post and this post. Reading this posts, will teach you how to query data in Firebase and how retrieve data from Firebase asynchronously.

Hope it helps.

Community
  • 1
  • 1
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I simply implemented the check if dataSnapshot exists and then go through if and else statement, but I have the same result.. – AlwaysConfused May 07 '17 at 12:53
  • Yes, but the reason why this is happening is because your method is executed after you reopen your activity. Please read those posts. – Alex Mamo May 07 '17 at 13:00
  • I did read both of the post, 1 of them is using addListenerForSingleValueEvent which has nothing to do with my question as I want to update the list items as soon as the data is changed inside the database and not just 1 time when the app is opened – AlwaysConfused May 07 '17 at 13:38