求助,SharedPreferences 只能保存用户名,不能记住密码

我照着视频教程敲的代码,commit也写了,config.xml文件导出来看了一下确实也保存了,请问到底是哪里出了问题,是配置文件里少什么权限吗?

public class MainActivity extends AppCompatActivity {

    private EditText mEt_username;
    private EditText mEt_userpassword;
    private CheckBox mCb_ischeck;
    private SharedPreferences mSp;
    private Button mBtn_login;

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

        //先初始化sp的实例
        /**
         * name 会自动生成"name.xml"文件
         * mode 模式
         */
        mSp = this.getSharedPreferences("config", MODE_PRIVATE);

        //找到控件
        mEt_username = (EditText) findViewById(R.id.et_username);
        mEt_userpassword = (EditText) findViewById(R.id.et_username);
        mCb_ischeck = (CheckBox) findViewById(R.id.cb_ischeck);
        mBtn_login = (Button) findViewById(R.id.btn_login);

        //在config.xml文件中取出数据,然后显示到EditText上
        String name = mSp.getString("name", "");
        String pwd = mSp.getString("pwd", "");
        mEt_username.setText(name);
        mEt_userpassword.setText(pwd);

    }

    public void login(View v) {

        String name = mEt_username.getText().toString().trim();
        String pwd = mEt_userpassword.getText().toString().trim();

        if (TextUtils.isEmpty(name) || (TextUtils.isEmpty(pwd))) {
            Toast.makeText(MainActivity.this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
        } else {
            if (mCb_ischeck.isChecked()) {
                //获取sp的编辑器
                SharedPreferences.Editor editor = mSp.edit();
                editor.putString("name", name);
                editor.putString("pwd", pwd);
                //记得把editor提交
                editor.commit();

                Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "请勾选cb", Toast.LENGTH_LONG).show();
            }
        }
    }
}
查看全部
voidCR
voidCR
2019/01/02 21:37
  • android-studio
  • android
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复