How to control storing user data using SharedPreferences when logging in and out?

后端 未结 3 940
再見小時候
再見小時候 2020-12-07 05:43

I\'m trying to create an app which uses username and password to login, then stay logged in as long as user didn\'t logout -or didn\'t delete app data of course-, and as far

3条回答
  •  广开言路
    2020-12-07 06:19

    What you have done is the right, the only thing is you have not committed your preference values.

    So your function will look like this

    public void doLogin(String username, String password) {
    
            Intent loginIntent = new Intent(LoginActivity.this, HomeActivity.class);
            SharedPreferences.Editor editor = perf.edit();
            editor.putString("username", username);
            editor.putString("password", password);
            editor.apply(); //This line will make necessary changes in SharedPreferences file
            startActivity(loginIntent);
            finish();
        }
    

    add the same line on button_logout click

    Moreover, I will recommend you to create a utility class for SharedPreference operations.

提交回复
热议问题