使用首选项保存用户名和密码

时间:2015-06-24 07:22:54

标签: android autocomplete preferences

我在使用偏好设置在我的应用中保存数据登录时遇到了麻烦。我已经在第一时间保存了用户名和密码,但下次我不知道如何在填写的字段用户名后保存自动填充/自动填充密码。有谁能够帮我。 Thanx这么多。

1 个答案:

答案 0 :(得分:6)

尝试此代码,这将有助于您:)

// Get SharedPreferences

 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

// set UI

  EditText username = (EditText) findViewById(R.id.username);
  EditText password = (EditText) findViewById(R.id.username);

// get value from existing preference


 strusername = sharedPreferences.getString("username", "");
 strpassword = sharedPreferences.getString("password", "");

// set existing value
username.setText(strusername);
password.setText(strpassword);

findViewById(R.id.login).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
            // put value in preference on button click
            Editor editor = sharedPreferences.edit();
            editor.putString("username", username.getText().toString());
            editor.putString("password", password.getText().toString());
            editor.commit();
        }
    });