Skip to content Skip to sidebar Skip to footer

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 wi

Solution 1:

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

Solution 2:

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.

Solution 3:

In the fisrt Activity where the user logged in , try to Save a variable on your SharedPreferences like this :

SharedPreferencessettings= getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editoreditor= settings.edit();
      editor.putBoolean("logged", true); // set it to false when the user is logged out// Commit the edits!
      editor.commit();

And then in every Activity of yours , put this code to check if the user is logged in or not , if he is not logged in , so redirect him to the LoginActivity like this :

@OverrideprotectedvoidonStart(Bundle state){
       super.onStart(state);
       . . .

       // Restore preferencesSharedPreferencessettings= getSharedPreferences(PREFS_NAME, 0);
       booleanloggedIn= settings.getBoolean("logged", true);
       if(!loggedIn){
            Toast.makeText(this,"you are not logged in !!",3000).show();
            Intenti=newIntent(this,LoginActivity.class);
            startActivity(i);
       }
    }

Post a Comment for "Check Login On Every Activity"