Ahmed El Sherif Ahmed El Sherif - 2 months ago 16
Android Question

onDataChange's value returns null

I'm trying to get data from my Firebase database
I have two Fragments, one for signing up and the other for signing in
I have no problems with inserting data into the Firebase, but somehow i'm unable to return the data from it

These are some codes from my sign in Fragment:

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}


I have this code inside
onCreate
method:

mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if(user != null)
{
getExistingUserInfo(user.getUid());
}
};


This is the method where i
query
the data from my
firebase


public void getExistingUserInfo(String uid){

final FirebaseDatabase database = FirebaseDatabase.getInstance();

database.getReference("allUsers").child(uid)
.orderByChild("emailAddress")
.equalTo(mEmailStr)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("Data Changed YEA!",dataSnapshot.toString());

}

@Override
public void onCancelled(DatabaseError databaseError) {
}

});


The problem is, when i launch the Application and
getExistingUserInfo
gets called inside
onCreate
, it returns the data of the last signed in user from my device correctly


> E/Data Changed YEA!: DataSnapshot { key =
> vWOypZ07sbeQKEtXnAwbEEV7ml43, value = {password=123456789,
> username=ahmed, sgl=true, emailAddress=ahmeddirect@gmail.com,
> studyGroupName=Study Group 2} }


But when I press sign in, it value returns null

E/Data Changed YEA!: DataSnapshot { key = vWOypZ07sbeQKEtXnAwbEEV7ml43, value = null }


So I have to close the application and reopen it in order to get the data correctly!!

The is the code where the user gets signed in, it's inside a
clickListener
in
onCreateView
method:

mAuth.signInWithEmailAndPassword(mEmailStr, mPasswordStr).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful())
{

Toast.makeText(getContext(),"Succeed!",Toast.LENGTH_LONG).show();

}
else
{
Toast.makeText(getContext(),"Failed!",Toast.LENGTH_LONG).show();
}
}
});


And this is how my
database
looks like:

Click to see the Image

Answer

Alright, first of all i don't see why you're using AuthStateListener Remove the code inside onStart, onStop and onCreate Replace your getExistingUserInfo with this

public void getExistingUserInfo() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String userID = user.getUid();
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    database.getReference("allUsers").child(userID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            hashMap = (HashMap<String, String>) dataSnapshot.getValue();
            List<String> dataS = new ArrayList<>(hashMap.values());

            for (String data : dataS) {
                Log.e("Database Data", data);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Post this method inside the onClickListener of the signin button and that should be it

Note: If you wanna do anything with the returned data then you should do it inside onDataChange after the data is returned

Comments