public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_pass = (EditText) findViewById(R.id.et_pass);
readAccount();
}
public void readAccount(){
//拿到一个SharedPreference对象
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
//从SharedPreference里取数据
String name = sp.getString("name", "");
String pass = sp.getString("pass", "");
et_name.setText(name);
et_pass.setText(pass);
}
public void login(View v){
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
//判断选框是否被勾选
if(cb.isChecked()){
//使用sharedPreference来保存用户名和密码
//路径在data/data/com.itheima.sharedpreference/share_
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
//拿到sp的编辑器
Editor ed = sp.edit();
ed.putString("name", name);
ed.putString("pass", pass);
//提交
ed.commit();
}
//创建并显示吐司对话框
Toast.makeText(this, "登录成功", 0).show();
}
}
使用SharedPreference存储账号密码
* 往SharedPreference里写数据
//拿到一个SharedPreference对象
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//拿到编辑器
Editor ed = sp.edit();
//写数据
ed.putBoolean("name", name);
ed.commit();
* 从SharedPreference里取数据
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//从SharedPreference里取数据
String name = sp.getBoolean("name", "");