关闭

用SharedPreferences存储数据

28人阅读 评论(0) 收藏 举报
分类:

public class MainActivity extends Activity implements OnClickListener {

private EditText et1, et2;
private CheckBox cb1;
private Button btn;
private SharedPreferences spf;
private Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findV();
spf = getSharedPreferences(“hello”, 0);
editor = spf.edit();
String userName = spf.getString(“et1”, “”);
if (userName == null) {
cb1.setChecked(false);
}
cb1.setChecked(true);
et1.setText(userName);
}

private void findV() {
et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
cb1 = (CheckBox) findViewById(R.id.cb1);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
String name = et1.getText().toString().trim();
String pass = et2.getText().toString().trim();
if (“admin”.equals(name) && “123456”.equals(pass)) {
if (cb1.isChecked()) {
editor.putString(“et1”, name);
editor.commit();
} else {
editor.remove(“et1”);
editor.commit();
}
Toast.makeText(this, “登录成功”, Toast.LENGTH_LONG).show();
}
Toast.makeText(this, “登录失败”, Toast.LENGTH_LONG).show();
break;

}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:265次
    • 积分:52
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档