Skip to content Skip to sidebar Skip to footer

Assignments Done Inside Valueeventlisteners Of Firebase Database Is Not Being Reflected

I have some global variables whose values need to be updated dynamically as per the database contains. So I tried using ValueEventListener() I can successfully read the intended v

Solution 1:

Firebase's ValueEventListener works asynchronously. That is why your logging code at the end, prints earlier than your asynchronous listener gets triggered. Data from firebase is indeed added(reflected) to the global variable, but after the log.

If you want to do some logic when firebase data changes you should do your logic directly inside the ValueEventListener or use LiveData or RxJava.

Here how to use LiveData:

publicclassMainActivityextendsAppCompatActivity {
    privatestatic final StringTAG = "MainActivity";

    privateStringRxuserId;
    publicArrayList<String> mToken;
    MutableLiveData<String> data = newMutableLiveData<>();

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RxuserId = intent.getStringExtra("Id");

        mToken = newArrayList<>();

        if(RxuserId != null){            
            database.getReference().child("users").child(RxuserId).addValueEventListener(newValueEventListener() {
                @OverridepublicvoidonDataChange(@NonNull DataSnapshot dataSnapshot) {
                    data.setValue(dataSnapshot.child("fcm token").getValue().toString());
                }

                @OverridepublicvoidonCancelled(@NonNull DatabaseError databaseError) {

                }
            });   
        }

        data.observe(this, newObserver<String>() {
            @OverridepublicvoidonChanged(String s) {
                mToken.add(s);
                Toast.makeText(getApplicationContext(), "REQUIRED TOKRN  " + s,Toast.LENGTH_LONG).show();

                Log.d(TAG,"REQUIRED TOKRN  " + string);
                Log.d(TAG,"REQUIRED TOKRN  " + mToken.size())
            }
        });
    }
}

This is not very useful case for LivaData. Usually LiveData is used when the logic with firebse is in another class (in Repository MVVM) to change UI according to data change.

List of users can be stored like this:

// User  is model class
List<User> users = newArrayList<>();

final MutableLiveData<List<User>> data = newMutableLiveData<>();

database.child("users").addValueEventListener(newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        List<User> users = newArrayList<>();

        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            Useruser= ds.getValue(User.class);
            users.add(user);
        }

        data.setValue(users); // data can be observed later
    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {

    }
});

Post a Comment for "Assignments Done Inside Valueeventlisteners Of Firebase Database Is Not Being Reflected"