使用SharedPreferences记住密码

使用SharedPreferences

 

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

     sp=getSharedPreferences("config",0);

    edit_name=(EditText) findViewById(R.id.name);
    edit_password=(EditText) findViewById(R.id.password);
    edit_remember=(CheckBox) findViewById(R.id.remember);
   //把config.xml文件中我们关心的数据取出来  然后显示到editText上
    String name=sp.getString("name","");
    String password=sp.getString("password","");

    edit_name.setText(name);
    edit_password.setText(password);
}
public void login(View v){

    String name=edit_name.getText().toString().trim();
    String password=edit_password.getText().toString().trim();
    //判断是否为空
    if(TextUtils.isEmpty(name)||TextUtils.isEmpty(password)){
        Toast.makeText(MainActivity.this,"用户名或密码为空",1).show();//1是时长
    }else{
        System.out.println("连接服务器,进行登入");
        if (edit_remember.isChecked()){
          //使用SharedPreferences去保存数据 拿到sp的实例
           // SharedPreferences sp=getSharedPreferences("config",0);
            //获取sp的编辑器

            Editor edit=sp.edit();
            edit.putString("name",name);
            edit.putString("password",password);
            //记得提交
            edit.commit();
        }
    }
}

public static Map<String ,String> readInfo(Context context){
    try{//定义Map
        Map<String,String> maps=new HashMap<String,String>();

        FileInputStream fis= context.openFileInput("infoo.txt");
        BufferedReader bufr=new BufferedReader(new InputStreamReader(fis));
        String content= bufr.readLine();//读取数据
        //切割字符串 封装到map集合中
        String[] splits=content.split("##");
        String name=splits[0];
        String password =splits[1];
        //把name 和 password 放入map中
        maps.put("name",name);
        maps.put("password",password);
        fis.close();
        return maps;
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex-panda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值