android初学之用户登录的判断

这里主要是用户名与密码的判断:

先用sharedpreferences方式存储数据,包含用户名和密码:username,password

然后在登录的时候进行判断:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
String name = et_username.getText().toString();
String password = et_password.getText().toString();

if (name.length() <= 0 && password.length() <= 0) {
Toast.makeText(LoginActivity.this, "用户名或密码为空", 0).show();
} else if (name.length() <= 0) {
Toast.makeText(LoginActivity.this, "用户名不能为空", 0).show();
} else if (password.length() <= 0) {
Toast.makeText(LoginActivity.this, "密码不能为空", 0).show();
} else if (name != null && password != null) {

// 获取存储的数据
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
String savename = sp.getString("username", "");
int savepassword = sp.getInt("password", 0);

//判断用户名与密码是否和保存的数据一致,进行提醒或者登录
if (savename.equals(name) && savepassword == Integer.parseInt(password)) {
//实现界面的跳转
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
//关闭当前界面
finish();
} else {
Toast.makeText(LoginActivity.this, "用户名或密码错误", 0).show();
}
}

扩展:其中判断用户名或密码是否为空时还可以使用name.isEmpty()判断是否为空,但是这个方法好像在JDK1.5以下版本是不能用的