LoginActivity:
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
finish();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
MainActivity:
public FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
//finish();
//startActivity(new Intent(MainActivity.this, LoginActivity.class));
} else {
Log.d(TAG, "THE USER IS NOT NULLL. his email is: " + firebaseUser.getEmail());
}
button.setOnClickListener(new OnClick(){
startActivity(new Intent(ActivityB.class));
});
}
ActivityB:
private FirebaseAuth firebaseAuth;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_friend);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Here the user is always null
}
Okay so the scenario that is happening:
I'm logging in successfully to the app, in MainActivity.java
it's printing that the user is not null. But when I press the button, ActivityB.java
is launching but the user and the FirebaseAuth
is always null.
I previously added a authListener
in MainActivity.java
and I figured out that whenever I start a new activity from the MainActivity the listener is triggered and its user would be null.
So why is the listener triggered when I start an Intent, and how do I access the firebaseAuth
and currentUser
from different activities?