I would like to get the following flow in my App:
I have everything, except to verify if the user is null
. I tried to do it but, the App closes and I get the error:
java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.firebase.auth.FirebaseAuth $ AuthStateListener.onAuthStateChanged (com.google.firebase.auth.FirebaseAuth)' on a null object reference
Apart from this, so that the Toast
appears, I must go to another Activity
and then return so that the Listener
is executed. Is not it supposed to work within the same Activity?
The idea is always to check if the user who is in the App is valid or not (example, if it has been deleted or if the account has been deactivated).
Code:
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class HomeActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mAuth = FirebaseAuth.getInstance();
mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener(){
@Override
public void onAuthStateChanged (@NonNull FirebaseAuth firebaseAuth){
if (mAuth.getCurrentUser() != null) {
Toast.makeText(HomeActivity.this, "User is not null", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HomeActivity.this, "User is null", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
I'm using:
implementation 'com.google.firebase:firebase-auth:16.0.3'
Any idea why it does not work for me?