//SQLite数据库存储登录验证
public class LoginActivity extends AppCompatActivity {
//声明共享存储(全局变量)
private SharedPreferences spf;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//在打开页面时初始化共享存储对象spf "users"表名
spf=getSharedPreferences("users", Context.MODE_PRIVATE);
//初始化数据库
MySQLiteOpenHelper sqLiteOpenHelper=new MySQLiteOpenHelper(LoginActivity.this,"users.db",null,1);
db=sqLiteOpenHelper.getReadableDatabase();
}
/**
* 登录
* @param view
*/
public void login(View view) {
//获取页面视图组件
EditText accountEt = findViewById(R.id.account);
EditText passwordEt = findViewById(R.id.password);
//获取用户名
String account = accountEt.getText().toString();
String password = passwordEt.getText().toString();
//表单验证
//判断用户名是否为空
if (account == null || "".equals(account)) {
showDialog("用户名不能为空!");
return;
}
//判断密码是否为空
if (password == null || "".equals(password)) {
showDialog("密码不能为空!");
return;
}
//验证登录,将用户输入的用户名和密码和共享存储里面的内容进行比对
String sql = "select * from users where account=? and password=?";
Cursor cursor = db.rawQuery(sql, new String[]{account, password});
/*if (account.equals(spf.getString("account",""))&&
password.equals(spf.getString("password",""))){
showDialog("登录成功!");
//登录成功后跳转到首页
Intent intent=new Intent(LoginActivity.this,HomeActivity.class);
//传递登录成功的用户名
intent.putExtra("account",account);
startActivity(intent);
}else{
showDialog("用户名或密码输入错误!");
}*/
if (cursor.moveToFirst()) {
//showDialog("登录成功!");
Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
//登录成功后跳转到首页
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//传递登录成功的用户名
intent.putExtra("account", account);
startActivity(intent);
} else {
showDialog("用户名或密码输入错误!");
}
}
//设置提示框
public void showDialog(String msg){
//1、创建AlertDialog.Builder对象
AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
//2、设置提示窗口相关信息
builder.setTitle("提示");
builder.setMessage(msg);//提示信息
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setCancelable(false);//点击空白区域不能被关掉 true能被关掉
builder.show();//显示提示框
}
}
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
/**
* 构造函数
* @param context
* @param name
* @param factory
* @param version
*/
public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库
String sql="create table users (" +
"id integer primary key autoincrement," +
"account text," +
"password text)";
db.execSQL(sql);
//插入一条数据
String sql2="insert into users (account,password) values ('admin','123')";
db.execSQL(sql2);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)