I'm developing and app where the user must login before using it. I customized my titlebar and put a logout button there, to enable users to logout whenever they want, and login with another account. The app should then display the login activity again.
That works well, but my problem is with the back button. When the user logs out, the login activity show up, but if he presses back, the app returns to the previous page, enabling the user to use that activity again, even without login.
I have my onCreate()
of every activity set up this way:
public void onCreate(Bundle savedInstanceState) {
// Activity code
checkLogin();
}
And the checkLogin()
:
if (GlobalContext.getCurrentUser() == null) {
Intent i = new Intent(this, LoginActivity.class);
startActivityForResult(i, GlobalContext.REQUEST_LOGIN);
}
However that's not working like it should, my app crashes sometimes when I press back, sometimes it return to the previous activity like I said, and sometimes it does actually work.
How can I make the checkLogin()
get called everytime the activity is (re)started?
Or there is another, better way to do what I want?
EDIT:
Based on @Gabriel's answer and the following diagram from the SDK references, I moved the checkLogin()
to the onResume()
method instead of the onCreate
, solving my problem.
What I suggest is to add you checkLogin()
to acitivity onResume()
as checking it in onCreate()
method will cause to call check for login 1 time only when activity created.
Or even batter is to move it to
onAttachToWindow()
So every time your activity will come to front. onAttachToWindow()
will be called and will check for login.
Move the call to checkLogin()
from onCreate()
to onStart()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With