Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check login on every activity

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.

Activity life cycle

like image 418
Rodrigo Castro Avatar asked Nov 23 '11 18:11

Rodrigo Castro


2 Answers

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.

like image 29
Arslan Anwar Avatar answered Sep 16 '22 15:09

Arslan Anwar


Move the call to checkLogin() from onCreate() to onStart().

like image 126
Gabriel Negut Avatar answered Sep 17 '22 15:09

Gabriel Negut