Search code examples
androidandroid-edittextandroid-buttonpassword-protectionandroid-sharedpreferences

Save that user entered right passwort (stay logged in)


I created a login activity (in code called: MainActivity) in which users have to enter a password (in this case: "test") and, if the passwort is correct, they were connect to the SuccessActivity. Until then everything works.

So, now, I want to save that the user entered the right password. I do this with:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final SharedPreferences sharedPreferences = getPreferences(this.MODE_PRIVATE);
    final EditText editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    final Button buttonLogin = (Button) findViewById(R.id.buttonLogin);

    buttonLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(editTextPassword.getText().toString().equals("test")) {
                Log.d("LOGIN", "Passwort right!");
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(PREF_NAME, "logged");
                editor.commit();
                startActivity(new Intent(MainActivity.this, SuccessActivity.class));
            }
            else {
                Toast.makeText(MainActivity.this,
                        "Passwort wrong!", Toast.LENGTH_LONG).show();
            }
        }
    });

After this, I want that the user, if he goes back or starts the app again, automatically opens the SuccessActivity. I do this with:

String Login = sharedPreferences.getString(PREF_NAME, "");
    if(Login.equals("test")) {
        Intent intent = new Intent(this, SuccessActivity.class);
        startActivity(intent);
    }
}

But, I think You can already think it, it does not work. If the password that the user entered is correct, the SucessActivity opens, but if the user opens the app again, he have to enter the passwort again.

I am new at working with SharedPreferences.


Solution

  • This is a simple fix. Let's take a look at what you're putting into SharedPreferences.

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(PREF_NAME, "logged");
    editor.commit();
    

    This is going to put the String "logged" into the preference PREF_NAME.

    Now let's take a look at what you're reading from SharedPreferences.

    String Login = sharedPreferences.getString(PREF_NAME, "");
    if(Login.equals("test")) {
    
    }
    

    As you can see, you are looking at the preference PREF_NAME and checking it it equals the String "test".

    Your problem is that "test" does not equal "logged".