求求啦,之前的代码还是好用的,自从加了数据库,想要保存电话记录,就不好用了
文件列表
LoginDBHelper.java
package com.example.zhaohuimima.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.zhaohuimima.entity.LoginInfor;
public class LoginDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME="login.db";
private static final String TABLE_NAME="login_infor";
//数据库的版本,当数据库更新了,或许会有新的功能增加进去,那么新的功能放在onUpgrade函数中
private static final int DB_VERSION=1;//当变成2的时候,想要增加两个字段,第一个版本为1
private static LoginDBHelper mHelper=null;
private SQLiteDatabase mRDB=null;
private SQLiteDatabase mWDB=null;
public LoginDBHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION);
}
//利用单例模式获取数据库帮助器的唯一实例
public static LoginDBHelper getInstance(Context context){
if(mHelper==null){
mHelper=new LoginDBHelper(context);
}
return mHelper;
}
//打开数据库的读连接
public void openReadLink(){
if(mRDB==null||!mRDB.isOpen()) {
mRDB = mHelper.getReadableDatabase();
}
}
//打开数据库的写连接
public void openWriteLink(){
if(mWDB==null||!mWDB.isOpen()) {
mWDB = mHelper.getWritableDatabase();
}
}
//数据库连接关闭
public void closeLink(){
if(mRDB!=null&&mRDB.isOpen()){
mRDB.close();
mRDB=null;
}
if(mWDB!=null&&mWDB.isOpen()){
mWDB.close();
mWDB=null;
}
}
@Override
public void onCreate(SQLiteDatabase db) {//创建数据库,执行建表语句
String sql="CREATE TABLE IF NOT EXISTS "+TABLE_NAME+" (" +
" id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
" phone VARCHAR NOT NULL,"+
" passWord VARCHAR NOT NULL," +
" remember INTEGER NOT NULL);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long inser(LoginInfor info){
ContentValues values=new ContentValues();
values.put("phone",info.phone);
values.put("passWord",info.passWord);
values.put("remember",info.remember);
return mWDB.insert(TABLE_NAME,null,values);
}
public void save(LoginInfor info){
//如果存在就先删除再添加
try{
mWDB.beginTransaction();
delete(info);
inser(info);
mWDB.setTransactionSuccessful();
}catch (Exception e){
e.printStackTrace();
}finally {
mWDB.endTransaction();
}
}
public long delete(LoginInfor info){
return mWDB.delete(TABLE_NAME,"phone=?",new String[]{info.phone});
}
// public List<User> queryAll(){//查询所有
// List<User> list=new ArrayList<>();
// //执行记录查询动作,该语句返回结果集的游标
// Cursor cursor=mRDB.query(TABLE_NAME,null,null,null,null,null,null);
// //循环取出游标指向的每条记录
// while (cursor.moveToNext()) {
// User user=new User();
// user.id=cursor.getInt(0);
// user.name=cursor.getString(1);
// user.age=cursor.getInt(2);
// user.height=cursor.getLong(3);
// user.weight=cursor.getFloat(4);
// //SQLite没有布尔型,用0表示false,用1表示true
// user.married=(cursor.getInt(5)==0)?false:true;
// list.add(user);
//
// }
// return list;
// }
public LoginInfor queryTop(){
LoginInfor info=null;
String sql="select * from "+TABLE_NAME+" where remember=1 ORDER BY _id DESC limit 1";
Cursor cursor=mRDB.rawQuery(sql,null);
if (cursor.moveToNext()) {
info=new LoginInfor();
info.id=cursor.getInt(0);
info.phone=cursor.getString(1);
info.passWord=cursor.getString(2);
info.remember=(cursor.getInt(3)==0)?false:true;
}
return info;
}
public LoginInfor queryByPhone(String phone){
LoginInfor info=null;
String sql="select * from "+TABLE_NAME;
Cursor cursor=mRDB.query(TABLE_NAME,null,"phone=? and remember=1",new String[]{phone},null,null,null);
if (cursor.moveToNext()) {
info=new LoginInfor();
info.id=cursor.getInt(0);
info.phone=cursor.getString(1);
info.passWord=cursor.getString(2);
info.remember=(cursor.getInt(3)==0)?false:true;
}
return info;
}
}
LoginInfor.java
package com.example.zhaohuimima.entity;
public class LoginInfor {
public int id;
public String phone;
public String passWord;
public boolean remember=false;
public LoginInfor(){
}
public LoginInfor(String phone, String passWord, boolean remember) {
this.phone = phone;
this.passWord = passWord;
this.remember = remember;
}
@Override
public String toString() {
return "LoginInfor{" +
"id=" + id +
", phone='" + phone + '\'' +
", passWord='" + passWord + '\'' +
", remember=" + remember +
'}';
}
}
LoginForgetActivity.java
package com.example.zhaohuimima;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class LoginForgetActivity extends AppCompatActivity implements View.OnClickListener {
private String mPhone;
private String mVerifyCode;
private EditText et_password_first;
private EditText et_password_secound;
private EditText et_verifycode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_forget);
et_password_first=findViewById(R.id.et_password_first);
et_password_secound=findViewById(R.id.et_password_secound);
et_verifycode=findViewById(R.id.et_verifycode);
//从上一个页面获取要修改密码的手机号
mPhone=getIntent().getStringExtra("phone");
findViewById(R.id.btn_verifcode).setOnClickListener(this);
findViewById(R.id.btn_confirm).setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_verifcode:
//点击获取验证码
//生成六位随机的验证码,范围:0-999999,如果是两位的话,就加上%06d中前面的0
mVerifyCode=String.format("%06d",new Random().nextInt(999999));
//弹出对话框,让用户记住这个六位数
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("请记住验证码");
builder.setMessage("手机号"+mPhone+",本次验证码是"+mVerifyCode+",请输入验证码");
builder.setPositiveButton("好的",null);
AlertDialog dialog=builder.create();
dialog.show();
break;
case R.id.btn_confirm:
//点击确定按钮
String passWord_first=et_password_first.getText().toString();
String passWord_secound=et_password_secound.getText().toString();
if(passWord_first.length()<6){
Toast.makeText(this,"请输入正确密码",Toast.LENGTH_SHORT).show();
return;
}
if(!passWord_first.equals(passWord_secound)){
Toast.makeText(this,"两次输入的密码不一致",Toast.LENGTH_SHORT).show();
return ;
}
if(!mVerifyCode.equals(et_verifycode.getText().toString())){
Toast.makeText(this,"验证码错误",Toast.LENGTH_SHORT).show();
return ;
}
Toast.makeText(this,"修改密码成功",Toast.LENGTH_SHORT).show();
//把修好的密码返回给下一个页面
Intent intent=new Intent();
intent.putExtra("new passWord",passWord_first);
setResult(Activity.RESULT_OK,intent);
finish();//当前页面结束,就是返回上一个页面
}
}
}
MainActivity.java
package com.example.zhaohuimima;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ViewUtils;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.zhaohuimima.database.LoginDBHelper;
import com.example.zhaohuimima.entity.LoginInfor;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, View.OnFocusChangeListener {
private TextView tv_password;
private EditText et_password;
private Button btn_forget;
private CheckBox ck_remember;
private EditText et_phone;
private RadioButton rb_password;
private RadioButton rb_verifycode;
private ActivityResultLauncher<Intent> register;
private Button btn_login;
private String mPassword="111111";
private String mVerifyCode;
private SharedPreferences preferences;
private LoginDBHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rb_login=findViewById(R.id.rg_login);
tv_password=findViewById(R.id.tv_password);
et_password=findViewById(R.id.et_password);
et_phone=findViewById(R.id.et_phone);
btn_forget=findViewById(R.id.btn_forget);
ck_remember=findViewById(R.id.ck_remember);
btn_forget=findViewById(R.id.btn_forget);
rb_password=findViewById(R.id.rb_password);
rb_verifycode=findViewById(R.id.rb_verifycode);
btn_login=findViewById(R.id.btn_login);
register=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {//得到新的密码
Intent intent=result.getData();
if(intent!=null && result.getResultCode()== Activity.RESULT_OK){
mPassword=intent.getStringExtra("new passWord");//更新密码
}
}
});
et_password.setOnFocusChangeListener(this);
//给rg_login设置单选监听器
rb_login.setOnCheckedChangeListener(this);
//给et_phone添加文本变更监听器
et_phone.addTextChangedListener(new HideTextWatcher(et_phone,11));
et_password.addTextChangedListener(new HideTextWatcher(et_password,6));
btn_forget.setOnClickListener(this);
btn_login.setOnClickListener(this);
}
private void reload(){
LoginInfor info=mHelper.queryTop();
if(info!=null && info.remember){
et_phone.setText(info.phone);
et_password.setText(info.passWord);
ck_remember.setChecked(true);
}
// boolean isRemember=preferences.getBoolean("isRemember",false);
// if(isRemember){
// String phone=preferences.getString("phone","");
// et_phone.setText(info.phone);
// String passWord=preferences.getString("passWord","");
// et_password.setText(info.passWord);
// ck_remember.setChecked(true);
// }
}
@Override
protected void onStart(){
super.onStart();
mHelper= LoginDBHelper.getInstance(this);
mHelper.openReadLink();
mHelper.openWriteLink();
reload();
}
@Override
protected void onStop() {
super.onStop();
mHelper.closeLink();
}
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
switch (checkedId){
case R.id.rb_password://密码登录
tv_password.setText(getString(R.string.login_password));
et_password.setHint(getString(R.string.input_password));
btn_forget.setText(getString(R.string.forget_password));
ck_remember.setVisibility(View.VISIBLE);
break;
case R.id.rb_verifycode://选择验证码登录
tv_password.setText(getString(R.string.verifycode));
et_password.setHint(getString(R.string.input_verifycode));
btn_forget.setText(getString(R.string.get_verifycode));
ck_remember.setVisibility(View.GONE);
break;
}
}
@Override
public void onClick(View view) {
String phone=et_phone.getText().toString();
if(phone.length()<11){
Toast.makeText(this,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
return ;
}
switch (view.getId()){
case R.id.btn_forget:
if(rb_password.isChecked()){//选择密码方式登录,跳到找回密码的界面
Intent intent=new Intent(this,LoginForgetActivity.class);
intent.putExtra("phone",phone);
register.launch(intent);
}else if(rb_verifycode.isChecked()){
//生成六位随机的验证码,范围:0-999999,如果是两位的话,就加上%06d中前面的0
mVerifyCode=String.format("%06d",new Random().nextInt(999999));
//弹出对话框,让用户记住这个六位数
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("请记住验证码");
builder.setMessage("手机号"+phone+",本次验证码是"+mVerifyCode+",请输入验证码");
builder.setPositiveButton("好的",null);
AlertDialog dialog=builder.create();
dialog.show();
}
break;
case R.id.btn_login:
//密码方式校验
if(rb_password.isChecked()){
if(!mPassword.equals(et_password.getText().toString())){
Toast.makeText(this,"请输入正确密码",Toast.LENGTH_SHORT).show();
return ;
}
//提示用户登录成功
loginSuccess();
}else if(rb_verifycode.isChecked()) {
//验证码方式检验
if (!mVerifyCode.equals(et_password.getText().toString())) {
Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
return;
}
//提示用户登录成功
loginSuccess();
}
break;
}
}
//验证通过,登陆成功
private void loginSuccess() {
String desc=String.format("您的手机号码是%s,恭喜你通过登录验证,点击“确定”按钮返回上个界面",
et_phone.getText().toString());
//以下弹出提醒对话框,提示用户登录成功
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("登录成功!");
builder.setMessage(desc);
builder.setNegativeButton("确定返回", (dialog,which)->{
//结束当前的活动页面
finish();
});
builder.setPositiveButton("我再看看",null);
AlertDialog dialog=builder.create();
dialog.show();
// if(ck_remember.isChecked()) {
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString("phone",et_phone.getText().toString());
// editor.putString("passWord",et_password.getText().toString());
// editor.putBoolean("isRemember",ck_remember.isChecked());
// editor.commit();
// }
//保存到数据库
LoginInfor info=new LoginInfor();
info.phone=et_phone.getText().toString();
info.passWord=et_password.getText().toString();
info.remember=ck_remember.isChecked();
mHelper.save(info);
}
@Override
public void onFocusChange(View view, boolean b) {
if(view.getId()==R.id.et_password && b){
LoginInfor info=mHelper.queryByPhone(et_phone.getText().toString());
//根据电话号码查到了密码
if(info!=null){
et_password.setText(info.passWord);
ck_remember.setChecked(info.remember);
}else{
//如果没有查到就清空
et_password.setText("");
ck_remember.setChecked(false);
}
}
}
//定义一个编辑框监听器,在输入文本达到指定长度是自动隐藏输入法
private class HideTextWatcher implements TextWatcher {
private EditText mView;
private int mMaxLength;
public HideTextWatcher(EditText v, int maxLength) {
this.mView=v;
this.mMaxLength=maxLength;
}
@Override
public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable s) {
if(s.toString().length()==mMaxLength){
// ViewUtil.hideOneInputMethod(MainActivity.this,mView);
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
}
activity_login_forget.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/item_layout_height"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/input_new_password"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size"/>
<EditText
android:id="@+id/et_password_first"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:hint="@string/input_new_password_hint"
android:background="@color/purple_200"
android:inputType="numberPassword"
android:maxLength="11"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textSize="@dimen/common_font_size"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/item_layout_height"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/confirm_new_password"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<EditText
android:id="@+id/et_password_secound"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:background="@color/purple_200"
android:hint="@string/input_new_password_again"
android:inputType="numberPassword"
android:maxLength="11"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textSize="@dimen/common_font_size" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/item_layout_height"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/verifycode2"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<EditText
android:id="@+id/et_verifycode"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:background="@color/purple_200"
android:hint="@string/input_verifycode"
android:inputType="numberPassword"
android:maxLength="11"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textSize="@dimen/common_font_size" />
<Button
android:id="@+id/btn_verifcode"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:text="@string/get_verifycode"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size" />
</RelativeLayout>
</LinearLayout>
<Button
android:id="@+id/btn_confirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/done"
android:textSize="@dimen/button_font_size" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<RadioGroup
android:id="@+id/rg_login"
android:layout_width="match_parent"
android:layout_height="@dimen/item_layout_height"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_password"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/login_by_password"
android:textSize="@dimen/common_font_size"
android:checked="true"/>
<RadioButton
android:id="@+id/rb_verifycode"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/login_by_verifycode"
android:textSize="@dimen/common_font_size"/>
</RadioGroup>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/item_layout_height"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/phone_number"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size"/>
<EditText
android:id="@+id/et_phone"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:hint="@string/input_phone_number"
android:background="@color/purple_200"
android:inputType="number"
android:maxLength="11"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textSize="@dimen/common_font_size"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/item_layout_height"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_password"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/login_password"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:background="@color/purple_200"
android:hint="@string/input_password"
android:inputType="numberPassword"
android:maxLength="11"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textSize="@dimen/common_font_size" />
<Button
android:id="@+id/btn_forget"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:text="@string/forget_password"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size" />
</RelativeLayout>
</LinearLayout>
<CheckBox
android:id="@+id/ck_remember"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/remember_password"
android:textColor="@color/black"
android:textSize="@dimen/common_font_size"/>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/login"
android:textSize="@dimen/button_font_size" />
</LinearLayout>
AndroidManifest.xml
效果