0

I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

Axis
  • 49
  • 1
  • 10

6 Answers6

1

The problem is that you are finishing the activity before starting the Intent..That is why it shows MainPage when the logout() is called..Instead, you will have to finish the activity after the intent has been called.

Thus replace your code as follows

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    //finish();       /****<-----commented out this line---****/
    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);

    finish();        /****<------Moved to here---****/
}

UPDATE

Since you are adding onClick attribute in your xml for the button and you are getting an error

java.lang.IllegalStateException: Could not find method logOut(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'logoutButton'

Replace your function as follows

void logOut(View v){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    //finish();       /****<-----commented out this line---****/
    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);

    finish();        /****<------Moved to here---****/
}

However, I dont think it's a good idea to solve this way. You should implement onClickListener inside your adapter or your fragment.

Lal
  • 14,726
  • 4
  • 45
  • 70
  • This still doesn't fix the problem :( – Axis Jun 05 '17 at 16:41
  • Now what is the problem? The `Authentication` activity is not shown? still the `MainPage` activity is being shown on `logOut()`? – Lal Jun 05 '17 at 16:42
  • Yep, the _Authentication_ is not showing and still the _Mainpage_ activity is being shown. – Axis Jun 05 '17 at 16:45
  • Are you sure that you replaced your code with the above one? Just check if the finish() is called after startActivity(). – Lal Jun 05 '17 at 16:47
  • Just to make sure it is working, please remove finish() from your code and check if the problem persists. – Lal Jun 05 '17 at 16:47
  • I've copy pasted your code to ensure that there is no syntax error, but I think there is a error in checking in Authentication (see my code for checking) – Axis Jun 05 '17 at 16:48
  • It still doesn't work even though I removed the `finish()` – Axis Jun 05 '17 at 16:49
  • Are you sure that the function logOut() is being called? – Lal Jun 05 '17 at 16:50
  • Yep, on `Authentication` I've commented out the startActivity and the Intent and it is pretty working – Axis Jun 05 '17 at 16:51
  • That means "blockSession.getBoolean("logged_in", false)" is returning false. There must might be some error where you are setting the value for "logged_in". Check it once more. – Lal Jun 05 '17 at 16:55
  • On _Authentication_, if the user has the right credentials, I called this function `blockEdit.putBoolean("logged_in", true);` – Axis Jun 05 '17 at 16:56
  • Sorry but I need to post it on [Pastebin](https://pastebin.com/eYi32fn5) :( Stackoverflow prevents me from doing it – Axis Jun 05 '17 at 17:04
  • It should be " if(!isLoggedIn){" instead of " if(isLoggedIn){". Right?? – Lal Jun 05 '17 at 17:06
  • Now it let me log out but now I cannot check if user is logged in – Axis Jun 05 '17 at 17:09
  • I've added a `finish()` on the if statement and on the `if(success)`, note that I've added them at the **end**, now when I click the log out button it just force close the app. – Axis Jun 05 '17 at 17:15
  • I dont understand what your problem actually is..you are starting authentication activity after logging out. And then in authentication activity, you check if user is logged in. It will always return false as you have already logged out. Then in your activity, if no one is logged in, you start the MainPage activity. This is what you have written and it works perfectly. What are you actually trying to achieve? – Lal Jun 05 '17 at 17:21
  • Sorry if I addressed my question so bad :( What i'm trying to do is fix the logout button, and if the user is logged in, redirect the user to Mainpage instead of staying at the Authentication – Axis Jun 05 '17 at 17:22
  • Try using getDefaultSharedPreferences() instead of getSharedPreferences() – Lal Jun 05 '17 at 17:27
  • I tried using getDefaultSharedPreferences, but now i'm getting this error when I click the logOut button, `java.lang.IllegalStateException: Could not find method logOut(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'logoutButton'` – Axis Jun 05 '17 at 17:36
  • Are you using any `View` in your `logOut()` function? – Lal Jun 05 '17 at 17:38
  • Check if you have `onClick` defined in your xml file for the logout button – Lal Jun 05 '17 at 17:39
  • I've imported View and Button, and I have `logOut` on my **onClick** – Axis Jun 05 '17 at 17:40
  • Please post your xml of the logout button – Lal Jun 05 '17 at 17:42
  • In which layout file do you have the logout button? Check if that layout file is used in the MainPage.java – Lal Jun 05 '17 at 17:49
  • It is on the `content_mainpage.xml` – Axis Jun 05 '17 at 17:51
  • Is the content_mainpage.xml being used for setContentView in MainPage.java? – Lal Jun 05 '17 at 17:53
  • Yes and no, `setContentView(R.layout.activity_mainpage);` it sets activity_mainpage where it use `content_mainpage.xml` – Axis Jun 05 '17 at 17:55
  • @Axis This is a different issue. I think you must ask this as a new question. – Lal Jun 05 '17 at 17:57
  • For your knowledge, If you set any onClick event in a layout file (xml), you have to create the method in the parent activity that will use that layout. – Lal Jun 05 '17 at 18:00
  • Also, instead of setting the `onClick` attribute in `xml` file, try setting the `onClickListener` of the logout button in your Java code. – Lal Jun 05 '17 at 18:02
  • @Axis Please check my updated answer and see if the error is resolved. – Lal Jun 05 '17 at 18:07
  • Yep, now I cannot see my username, money, etc.. but when I click the logout button it stills kept me redirecting to the **Mainpage**. – Axis Jun 06 '17 at 05:57
  • This is how I add the logged_in value, `...if(success){SharedPreferences blockSession = getSharedPreferences("blockSession", 0);SharedPreferences.Editor blockEdit = blockSession.edit();blockEdit.putBoolean("logged_in", true);...blockEdit.apply();[Intent code]finish();` – Axis Jun 06 '17 at 05:58
0

Try this, hope it helps

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.commit(); // to apply the changes
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
Collins Abitekaniza
  • 4,496
  • 2
  • 28
  • 43
  • I've tested it and no, it doesn't work. I tried checking the logcat but apparently every time I press the button there is a error flashing then it instantly gone. – Axis Jun 05 '17 at 16:30
0

Try it.

 SharedPreferences mySPref = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = mySPrefs.edit();
        editor.remove(String key);
        editor.apply();
halfer
  • 19,824
  • 17
  • 99
  • 186
Muhammad Waqas
  • 420
  • 4
  • 19
0

Replace your this line of code

 blockEdit.apply();

with

 blockEdit.commit();

Followed by your activity calling intent.Hope it helps.

mdb
  • 166
  • 8
  • I think it is better to use apply rather than commit. [See this](https://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference) – Axis Jun 05 '17 at 16:59
0

Put finish() here in the code of yours

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0); 
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}


UPDATE
I went through your code and found a small mistake in it :
In your OnCreate method you are using :

SharedPreferences blockSession  = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isLoggedIn  = blockSession.getBoolean("logged_in", false);
    if(!isLoggedIn){
        Intent intent  = new Intent(this, Mainpage.class);
        startActivity(intent);
        finish();
    }

Mistakes :
You are getting your sharedPreference value in on create method But when you are clearing sharedPreference on logout it doesn't have any shaved sharedPreference value . so it takes false as default value as you mentioned here :

 boolean isLoggedIn  = blockSession.getBoolean("logged_in", false); // false is default value.

And you if conditioned is always true because you have false value every time you logout.

Solution :
change if condition as follows :

if(isLoggedIn){
        Intent intent  = new Intent(this, Mainpage.class);
        startActivity(intent);
        finish();
    }
Amit Sharma
  • 645
  • 5
  • 13
  • Doing that force closes the application, `java.lang.IllegalStateException: Could not find method logOut(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'logoutButton'` – Axis Jun 05 '17 at 16:58
  • Please share your code .. put that class on GitHub and share links . – Amit Sharma Jun 05 '17 at 20:35
  • @Axis I found the mistakes .. i will update my answer soon – Amit Sharma Jun 06 '17 at 06:29
0

Just reset your SharedPreferences KEY logged_in value to false using blockEdit.putBoolean("logged_in", false) and commit.

Try this:

void logOut(View view) {

    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();

    // Set logged_in value to false
    blockEdit.putBoolean("logged_in", false);
    blockEdit.commit();

    // Start Authentication     
    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);

    // Finish MainPage 
    finish();
}

#. Best practice is to create a common class for session management and use this from anywhere in your application as per your needs.

Crate a SessionManager class like below:

public class SessionManager {

    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    Context context;

    // Shared Preferences
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "MY_APP";

    private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";

    private static final String KEY_USER_ID = "USER_ID";
    private static final String KEY_USER_EMAIL = "USER_EMAIL";
    private static final String KEY_USER_USERNAME = "USER_USERNAME";

    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = sharedPreferences.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public void setUserId(int id) {
        editor.putInt(KEY_USER_ID, id);
        editor.commit();
    }

    public int getUserId() {
        return sharedPreferences.getInt(KEY_USER_ID, 0);
    }

    public void setUsername(String username) {
        editor.putString(KEY_USER_USERNAME, username);
        editor.commit();
    }

    public String getUsername() {
        return sharedPreferences.getString(KEY_USER_USERNAME, "user1234");
    }

    public void setEmail(String email) {
        editor.putString(KEY_USER_EMAIL, email);
        editor.commit();
    }

    public String getEmail() {
        return sharedPreferences.getString(KEY_USER_EMAIL, "default@gmail.com");
    }
}

USE:

LOGIN:

SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);
sessionManager.setUserId(userId);

// Launch MainPage
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();

LOGOUT:

SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);

// Launch LoginPage
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();

Hope this will help~

Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
  • I tried this but this doesn't work. By the way, this is how I get my SharedPreferences when the user has the right crendentials, [It is inside a function] `SharedPreferences blockSession = getSharedPreferences("blockSession", 0);` – Axis Jun 06 '17 at 05:55
  • I have used this process in my app its working flawlessly. – Ferdous Ahamed Jun 06 '17 at 05:57
  • Put some log in your logOut method before and after setting or clearing sharedPreferences value and check weather its working or not. – Ferdous Ahamed Jun 06 '17 at 05:59
  • Check my updated answer. Best practice is to create a common class for session and use it from anywhere in your app. – Ferdous Ahamed Jun 06 '17 at 06:07