Skip to content Skip to sidebar Skip to footer

Android Login/registration Using Sharedpreference

I'm trying to make a Login/Registration activity by using sharedpreference. The app will only hold one login/password information. So on original start up the app will check if the

Solution 1:

finalSharedPreferencessharedPref= PreferenceManager.getDefaultSharedPreferences(this);
Registered = sharedPref.getBoolean("Registered", false);

if (!Registered) {

    Loginbutton.setVisibility(View.GONE);
    RegisterButton.setVisibility(View.VISIBLE);

    // If the user is registered already.
} else{

    Loginbutton.setVisibility(View.VISIBLE);
    RegisterButton.setVisibility(View.GONE);
}

RegisterButton.setOnClickListener(newView.OnClickListener() {
    @OverridepublicvoidonClick(View v) {
        Username_input = (EditText) findViewById(R.id.Username_input);
        Password_input = (EditText) findViewById(R.id.Password_input);
        Username = Username_input.getText().toString();
        Password = Password_input.getText().toString();

        SharedPreferences.Editoreditor= sharedPref.edit();
        editor.putBoolean("Registered", true);
        editor.putString("Username", Username);
        editor.putString("Password", Password);
        editor.apply();

        finish();
        startActivity(getIntent());

    }
});

Solution 2:

add editor.commit() after you put the value into preferences.

 SharedPreferences.Editoreditor= sharedPref.edit();
 editor.putBoolean("Registered", Registered);
 editor.putString("Username", Username);
 editor.putString("Password", Password);
 editor.commit();

Solution 3:

You are making two mistakes :

  • not fetching the registered value from shared preferences before checking it's value initially.
  • not doing editor.apply () or editor.commit() after putting new values.

Solution 4:

try this (no need of taking shared pref as final)

SharedPreferencessharedPref= getContext().getSharedPreferences("hello", getContext().MODE_PRIVATE);

Booleanregister= sharedPref.getBoolean("key",true);

and inside register.onClick

SharedPreferences sharedPref = getContext().getSharedPreferences("hello", getContext().MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPref.edit();
//your rest of the code to put string values into shared pref here.
editor.putBoolean("key",false);
editor.apply();

Post a Comment for "Android Login/registration Using Sharedpreference"