Reputation:
I have setup firebase email and password login. I have three activities in my app. Register, Login and Main. In main activity, I have put Firebase AuthSateListener to detect if user exists, if not send the user to login/register activities.
The problem I guess is that my MainActivity is my launcher activity and even if there's no currently logged in user, it does not redirect to the auth activities. I don't know if my assumption is right or I'm not setting it up correctly. Here's my code so far:
public class MainActivity extends BaseActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView playersRV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null){
Log.d(TAG, "User is null");
startActivity(new Intent(MainActivity.this, LoginActivity.class));
} else {
Log.d(TAG, "User exists:\t" + user.getEmail());
return;
}
}
};
playersRV.setHasFixedSize(true);
playersRV.setLayoutManager(new LinearLayoutManager(this));
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAuth.signOut();
mAuth = null;
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
private void init() {
playersRV = findViewById(R.id.playersRV);
}
@Override
protected void onStart() {
super.onStart();
if (authStateListener == null){
mAuth.addAuthStateListener(authStateListener);
}
}
@Override
protected void onStop() {
super.onStop();
if (authStateListener != null){
mAuth.removeAuthStateListener(authStateListener);
authStateListener = null;
}
}
}
My BaseActivity has variable declarations for Firebase Auth and Firebase AuthStateListener.
Can anyone tell me why this is happening this way? Thanks.
Upvotes: 1
Views: 110
Reputation: 2496
You can try this,
//Get Firebase auth instance
FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
// User is logged in - send it to home screen \\
} else {
//User is not logged in - send it to login screen \\
}
Upvotes: 1