Android Firebase addListenerForSingleValueEvent is not working

前端 未结 1 1306
囚心锁ツ
囚心锁ツ 2020-12-04 02:36

I know this has been asked a lot but I still can get it to work. Here\'s my code:

private int test;

DatabaseReference rootRef = FirebaseDatabase.getInstance         


        
相关标签:
1条回答
  • 2020-12-04 03:20

    The data is loaded from Firebase asynchronously. By the time your log test, the onDataChange hasn't run yet.

    To see this in action, add some more logging inside onDataChange:

    private int test;

    test = 0;
    userRef.addListenerForSingleValueEvent(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(userID)) {
                test = 1;
            }
            else {
                test = 2;
            }
            Log.d(TAG, "Test2 = " + test);
       }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // Don't ignore errors
        }
    });
    
    Log.d(TAG, "Test = " + test);
    

    Now you'll first see:

    Test = 0

    And then once the data has loaded and onDataChange gets called:

    Test = 1

    or

    Test = 2

    For this reason you should always put (or call) the code that needs the data from the database from within onDataChange().

    0 讨论(0)
提交回复
热议问题