hagrya hagrya - 3 years ago 168
Android Question

Firebase Pushing Data in One Activity and Retrieving Data in Another Activity

I have three activites Register,Login and Main.When user enter his registrationg details,i am pushing the email id to firebase database after successfull registration.The userdetails is successfully pushed.Now it opens MainActivity
Foll is the code in my RegisterActivity

mFirebaseDatabase = FirebaseDatabase.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("loginusers");
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this,"Registration Success",Toast.LENGTH_LONG).show();
saveDisplayName();

User user = new User(email);
mMessagesDatabaseReference.push().setValue(user);
......}


Now i want to retieve all the users which are registered in my MainActivitie's ArrayList. So i wrote the foll code in my MainActivity

mFirebaseDatabase = FirebaseDatabase.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("loginusers");
mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
contactList.clear();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {

User user = postSnapshot.getValue(User.class);
if(!contactList.contains(user)){
contactList.add(user);


}

}
for(int i=0;i<contactList.size();i++){
Toast.makeText(getApplicationContext(),"Hi"+contactList.get(i),Toast.LENGTH_SHORT).show();
Log.i("Pritish", "onDataChange: "+contactList.get(i));
}

}

@Override
public void onCancelled(DatabaseError databaseError) {



}
});


but this method never gets called.Now i know i can write the code written in my MainActivity in RegisterActivity and then pass the userlist using an Intent but i don't want to do that as it may create a problem if the user is using LoginActivity.
Please help

Answer Source

To solve this, you need to declare and use the contactList in the onDataChange() method otherwise it will be always null because of the asynchronous behaviour of this methods which is called even before you are adding those objects to the list. So your code should look like this:

mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            List<User> contactList = new ArrayList<>();

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                User user = postSnapshot.getValue(User.class);
                if(!contactList.contains(user)){
                    contactList.add(user);
                }
            }
            for(int i=0;i<contactList.size();i++){
                Toast.makeText(getApplicationContext(),"Hi"+contactList.get(i),Toast.LENGTH_SHORT).show();
                Log.i("Pritish", "onDataChange: "+contactList.get(i));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
});

If you want to use the value of that String outside that method, please take a look at my answer from this post.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download