Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android. How to save user name and password after the app is closed?

I am writing an application with login details (username and password).
I want to make it so that when the user closes the application and starts it again later he/she doesn't have to enter his/her user name and password again.

So here is my code so far. It doesn't seem to remember the password nor the username, unfortunately for me:

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mPrefs = getSharedPreferences(PREFS, 0);
    final CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.saveLoginCheckBox);

    boolean rememberMe = mPrefs.getBoolean("rememberMe", false);



    if (android.os.Build.VERSION.SDK_INT > 9)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    mXmlRpcClient = new XMLRPCClient(mXmlRpcUri);

    // Set up the login form.
    //mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
    mUsernameView = (EditText) findViewById(R.id.username);
    mUsernameView.setText(mUsername);

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int id,
                        KeyEvent keyEvent) {
                    if (id == R.id.login || id == EditorInfo.IME_NULL) {
                        attemptLogin();
                        return true;
                    }
                    return false;
                }
            });

    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    findViewById(R.id.sign_in_button).setOnClickListener
    (
            new View.OnClickListener()
            {
                @Override
                public void onClick(View view) 
                {
                    if(rememberMeCbx.isChecked())
                    {
                        attemptLogin(); //function to check if fields are filled correctly
                        saveLoginDetails();
                    }
                    else
                    {
                        attemptLogin();
                        removeLoginDetails();
                    }

                }
            });

    if(rememberMe == true)
    {
        //get previously stored login details
        String login = mPrefs.getString("mUsername", null);
        String upass = mPrefs.getString("mPassword", null);

        if(login != null && upass != null)
        {
            //fill input boxes with stored login and pass
            EditText loginEbx = (EditText)findViewById(R.id.username);
            EditText passEbx = (EditText)findViewById(R.id.password);
            loginEbx.setText(login);
            passEbx.setText(upass);

            //set the check box to 'checked'                
            rememberMeCbx.setChecked(true);
        }
    }
}



/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            mSessionID = (String)mXmlRpcClient.call(mLoginFuncName, mUsername, mPassword);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
            Intent intent = new Intent(LoginActivity.this, MainWindow.class);
            intent.putExtra("SessionID", mSessionID);
            intent.putExtra("XmlRpcUrl", mXmlRpcUrl);
            intent.putExtra("LoginFuncName", mLoginFuncName);
            intent.putExtra("LogoutFuncName", mLogoutFuncName);
            intent.putExtra("GetDevicesFuncName", mGetDevicesFuncName);
            intent.putExtra("SendPositionFuncName", mSendPositionFuncName);
            intent.putExtra("GetSavedTripFunc", mGetSavedTripFunc);             
            startActivity(intent);
        } else {
            mPasswordView
                    .setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }


}

private void saveLoginDetails()
{
    //fill input boxes with stored login and pass
    EditText loginEbx = (EditText)findViewById(R.id.username);
    EditText passEbx = (EditText)findViewById(R.id.password);
    String login = loginEbx.getText().toString();
    String upass = passEbx.getText().toString();

    Editor e = mPrefs.edit();
    e.putBoolean("rememberMe", true);
    e.putString("login", login);
    e.putString("password", upass);
    e.commit();
}

private void removeLoginDetails()
{
    Editor e = mPrefs.edit();
    e.putBoolean("rememberMe", false);
    e.remove("login");
    e.remove("password");
    e.commit();
}

}

Can you tell me what is wrong with my code and how can I improve it so that the user name and password are saved and retrieved after the application is closed and opened again?

like image 368
user3182266 Avatar asked Feb 11 '14 08:02

user3182266


People also ask

How do I keep my account logged in on the app?

When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out. Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.

What is user credentials?

User credentials are typically a username and password combination used for logging in to online accounts. However, they can be combined with more secure authentication tools and biometric elements to confirm user identities with a greater degree of certainty.

What is Android app password?

An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on.


1 Answers

Try this way: defined Preferences first

private static final String PREFS_NAME = "preferences";
private static final String PREF_UNAME = "Username";
private static final String PREF_PASSWORD = "Password";

private final String DefaultUnameValue = "";
private String UnameValue;

private final String DefaultPasswordValue = "";
private String PasswordValue;

And onPause()

@Override
public void onPause() {
    super.onPause();
    savePreferences();

}

And onResume()

@Override
public void onResume() {
    super.onResume();
    loadPreferences();
     }

And here savePreferences()

private void savePreferences() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Edit and commit
    UnameValue = edt_username.getText();
    PasswordValue = edt_password.getText();
    System.out.println("onPause save name: " + UnameValue);
    System.out.println("onPause save password: " + PasswordValue);
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.commit();
}

And here loadPreferences()

private void loadPreferences() {

    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    // Get value
    UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
    PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
    edt_username.setText(UnameValue);
    edt_password.setText(PasswordValue);
    System.out.println("onResume load name: " + UnameValue);
    System.out.println("onResume load password: " + PasswordValue);
}
like image 179
M D Avatar answered Sep 30 '22 16:09

M D