android - Firebase return null value from datasnapshot Why?

前端 未结 1 380
走了就别回头了
走了就别回头了 2021-01-26 08:33

I am having some touble with the following code snipped:

mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    publi         


        
相关标签:
1条回答
  • 2021-01-26 09:00

    The data is loaded from Firebase asynchronously. This means that the order in which your code is execute is not what you're likely expecting. You can most easily see this by adding a few log statements to the code:

    System.out.println("Before addListenerForSingleValueEvent");
    mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void  onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("In onDataChange");
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
    System.out.println("After addListenerForSingleValueEvent");
    

    The output of this is:

    Before addListenerForSingleValueEvent

    After addListenerForSingleValueEvent

    In onDataChange

    This is probably not what you expected! The data is loaded from Firebase asynchronously. And instead of waiting for it to return (which would cause an "Application Not Responding" dialog), the method continues. Then when the data is available, your onDataChange is invoked.

    To make the program work, you need to move the code that needs the data into the onDataChange method:

    mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void  onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("size ="+dataSnapshot.getChildrenCount());
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
    
    0 讨论(0)
提交回复
热议问题