当前位置:   article > 正文

Android Studio App开发中数据库SQLite的解析及实战使用(包括创建数据库,增删改查,记住密码等 附源码必看)_android studio sqlite

android studio sqlite

运行有问题或需要源码请点赞关注收藏后评论区留言~~~

SQLite简介

SQLite是一种小巧的嵌入式数据库,使用方便,开发简单,如同mysql,oracle那样,SQLite也采用SQL语句管理数据,由于它属于轻型数据库,不涉及复杂的数据控制操作,因此App开发只用到数据定义和数据操纵两类SQL。

1:数据定义语言

它描述了怎么变更数据实体的框架结构,就SQLite而言,主要包括创建表格,删除表格,修改表结构等等操作

2:数据操纵语言

它描述了怎样处理数据实体的内部记录,表格记录的操作类型包括添加,删除,修改,查询4类

一、数据库管理器SQLiteDatabase

若要在Java代码中操纵SQLite,还需要专门的工具类,SQLiteDatabase便是Android提供的SQLite数据库管理器,开发者可以在活动页面代码调用openOrCreateDatabase方法获取数据库实例 效果如下

 

DatabaseActivity类

  1. package com.example.chapter06;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.TextView;
  7. import androidx.appcompat.app.AppCompatActivity;
  8. public class DatabaseActivity extends AppCompatActivity implements View.OnClickListener {
  9. private TextView tv_database;
  10. private String mDatabaseName;
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_database);
  15. tv_database = findViewById(R.id.tv_database);
  16. findViewById(R.id.btn_database_create).setOnClickListener(this);
  17. findViewById(R.id.btn_database_delete).setOnClickListener(this);
  18. // 生成一个测试数据库的完整路径
  19. mDatabaseName = getFilesDir() + "/test.db";
  20. }
  21. @Override
  22. public void onClick(View v) {
  23. if (v.getId() == R.id.btn_database_create) {
  24. // 创建或打开数据库。数据库如果不存在就创建它,如果存在就打开它
  25. SQLiteDatabase db = openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE, null);
  26. String desc = String.format("数据库%s创建%s", db.getPath(), (db!=null)?"成功":"失败");
  27. tv_database.setText(desc);
  28. } else if (v.getId() == R.id.btn_database_delete) {
  29. boolean result = deleteDatabase(mDatabaseName); // 删除数据库
  30. String desc = String.format("数据库%s删除%s", mDatabaseName, result?"成功":"失败");
  31. tv_database.setText(desc);
  32. }
  33. }
  34. }

activity_databaseXML文件

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical">
  5. <LinearLayout
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content"
  8. android:orientation="horizontal">
  9. <Button
  10. android:id="@+id/btn_database_create"
  11. android:layout_width="0dp"
  12. android:layout_height="wrap_content"
  13. android:layout_weight="1"
  14. android:text="创建数据库"
  15. android:textColor="@color/black"
  16. android:textSize="17sp" />
  17. <Button
  18. android:id="@+id/btn_database_delete"
  19. android:layout_width="0dp"
  20. android:layout_height="wrap_content"
  21. android:layout_weight="1"
  22. android:text="删除数据库"
  23. android:textColor="@color/black"
  24. android:textSize="17sp" />
  25. </LinearLayout>
  26. <TextView
  27. android:id="@+id/tv_database"
  28. android:layout_width="match_parent"
  29. android:layout_height="wrap_content"
  30. android:paddingLeft="5dp"
  31. android:textColor="@color/black"
  32. android:textSize="17sp" />
  33. </LinearLayout>

二、数据库帮助器SQLiteOpenHelper

由于SQLiteDatabase存在局限性,一不小心就会重复打开数据库,处理数据库的升级也不方便,因此Android提供了数据库帮助其SQLiteOpenHelper,帮助开发者合理使用SQLite

下面通过实例演示对数据库的增删改查功能以及获取用户信息 效果如下

 

 

SQLiteWriteActivity类 

  1. package com.example.chapter06;
  2. import android.os.Bundle;
  3. import android.text.TextUtils;
  4. import android.view.View;
  5. import android.widget.CheckBox;
  6. import android.widget.CompoundButton;
  7. import android.widget.EditText;
  8. import androidx.appcompat.app.AppCompatActivity;
  9. import com.example.chapter06.bean.UserInfo;
  10. import com.example.chapter06.database.UserDBHelper;
  11. import com.example.chapter06.util.DateUtil;
  12. import com.example.chapter06.util.ToastUtil;
  13. public class SQLiteWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
  14. private UserDBHelper mHelper; // 声明一个用户数据库帮助器的对象
  15. private EditText et_name;
  16. private EditText et_age;
  17. private EditText et_height;
  18. private EditText et_weight;
  19. private boolean bMarried = false;
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_sqlite_write);
  24. et_name = findViewById(R.id.et_name);
  25. et_age = findViewById(R.id.et_age);
  26. et_height = findViewById(R.id.et_height);
  27. et_weight = findViewById(R.id.et_weight);
  28. CheckBox ck_married = findViewById(R.id.ck_married);
  29. ck_married.setOnCheckedChangeListener(this);
  30. findViewById(R.id.btn_save).setOnClickListener(this);
  31. }
  32. @Override
  33. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  34. bMarried = isChecked;
  35. }
  36. @Override
  37. protected void onStart() {
  38. super.onStart();
  39. // 获得数据库帮助器的实例
  40. mHelper = UserDBHelper.getInstance(this, 1);
  41. mHelper.openWriteLink(); // 打开数据库帮助器的写连接
  42. }
  43. @Override
  44. protected void onStop() {
  45. super.onStop();
  46. mHelper.closeLink(); // 关闭数据库连接
  47. }
  48. @Override
  49. public void onClick(View v) {
  50. if (v.getId() == R.id.btn_save) {
  51. String name = et_name.getText().toString();
  52. String age = et_age.getText().toString();
  53. String height = et_height.getText().toString();
  54. String weight = et_weight.getText().toString();
  55. if (TextUtils.isEmpty(name)) {
  56. ToastUtil.show(this, "请先填写姓名");
  57. return;
  58. } else if (TextUtils.isEmpty(age)) {
  59. ToastUtil.show(this, "请先填写年龄");
  60. return;
  61. } else if (TextUtils.isEmpty(height)) {
  62. ToastUtil.show(this, "请先填写身高");
  63. return;
  64. } else if (TextUtils.isEmpty(weight)) {
  65. ToastUtil.show(this, "请先填写体重");
  66. return;
  67. }
  68. // 以下声明一个用户信息对象,并填写它的各字段值
  69. UserInfo info = new UserInfo();
  70. info.name = name;
  71. info.age = Integer.parseInt(age);
  72. info.height = Long.parseLong(height);
  73. info.weight = Float.parseFloat(weight);
  74. info.married = bMarried;
  75. info.update_time = DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss");
  76. mHelper.insert(info); // 执行数据库帮助器的插入操作
  77. ToastUtil.show(this, "数据已写入SQLite数据库");
  78. }
  79. }
  80. }

SQLiteReadActivity类

  1. package com.example.chapter06;
  2. import android.annotation.SuppressLint;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.widget.TextView;
  6. import androidx.appcompat.app.AppCompatActivity;
  7. import com.example.chapter06.bean.UserInfo;
  8. import com.example.chapter06.database.UserDBHelper;
  9. import com.example.chapter06.util.ToastUtil;
  10. import java.util.List;
  11. @SuppressLint("DefaultLocale")
  12. public class SQLiteReadActivity extends AppCompatActivity implements View.OnClickListener {
  13. private UserDBHelper mHelper; // 声明一个用户数据库帮助器的对象
  14. private TextView tv_sqlite;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_sqlite_read);
  19. tv_sqlite = findViewById(R.id.tv_sqlite);
  20. findViewById(R.id.btn_delete).setOnClickListener(this);
  21. }
  22. @Override
  23. protected void onStart() {
  24. super.onStart();
  25. // 获得数据库帮助器的实例
  26. mHelper = UserDBHelper.getInstance(this, 1);
  27. mHelper.openReadLink(); // 打开数据库帮助器的读连接
  28. readSQLite(); // 读取数据库中保存的所有用户记录
  29. }
  30. @Override
  31. protected void onStop() {
  32. super.onStop();
  33. mHelper.closeLink(); // 关闭数据库连接
  34. }
  35. // 读取数据库中保存的所有用户记录
  36. private void readSQLite() {
  37. if (mHelper == null) {
  38. ToastUtil.show(this, "数据库连接为空");
  39. return;
  40. }
  41. // 执行数据库帮助器的查询操作
  42. List<UserInfo> userList = mHelper.query("1=1");
  43. String desc = String.format("数据库查询到%d条记录,详情如下:", userList.size());
  44. for (int i = 0; i < userList.size(); i++) {
  45. UserInfo info = userList.get(i);
  46. desc = String.format("%s\n第%d条记录信息如下:", desc, i + 1);
  47. desc = String.format("%s\n 姓名为%s", desc, info.name);
  48. desc = String.format("%s\n 年龄为%d", desc, info.age);
  49. desc = String.format("%s\n 身高为%d", desc, info.height);
  50. desc = String.format("%s\n 体重为%f", desc, info.weight);
  51. desc = String.format("%s\n 婚否为%b", desc, info.married);
  52. desc = String.format("%s\n 更新时间为%s", desc, info.update_time);
  53. }
  54. if (userList.size() <= 0) {
  55. desc = "数据库查询到的记录为空";
  56. }
  57. tv_sqlite.setText(desc);
  58. }
  59. @Override
  60. public void onClick(View v) {
  61. if (v.getId() == R.id.btn_delete) {
  62. mHelper.closeLink(); // 关闭数据库连接
  63. mHelper.openWriteLink(); // 打开数据库帮助器的写连接
  64. mHelper.deleteAll(); // 删除所有记录
  65. mHelper.closeLink(); // 关闭数据库连接
  66. mHelper.openReadLink(); // 打开数据库帮助器的读连接
  67. readSQLite(); // 读取数据库中保存的所有用户记录
  68. ToastUtil.show(this, "已删除所有记录");
  69. }
  70. }
  71. }

activity_sqlite_writeXML文件

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical"
  5. android:padding="5dp" >
  6. <RelativeLayout
  7. android:layout_width="match_parent"
  8. android:layout_height="40dp" >
  9. <TextView
  10. android:id="@+id/tv_name"
  11. android:layout_width="wrap_content"
  12. android:layout_height="match_parent"
  13. android:gravity="center"
  14. android:text="姓名:"
  15. android:textColor="@color/black"
  16. android:textSize="17sp" />
  17. <EditText
  18. android:id="@+id/et_name"
  19. android:layout_width="match_parent"
  20. android:layout_height="match_parent"
  21. android:layout_marginBottom="3dp"
  22. android:layout_marginTop="3dp"
  23. android:layout_toRightOf="@+id/tv_name"
  24. android:background="@drawable/editext_selector"
  25. android:gravity="left|center"
  26. android:hint="请输入姓名"
  27. android:inputType="text"
  28. android:maxLength="12"
  29. android:textColor="@color/black"
  30. android:textSize="17sp" />
  31. </RelativeLayout>
  32. <RelativeLayout
  33. android:layout_width="match_parent"
  34. android:layout_height="40dp" >
  35. <TextView
  36. android:id="@+id/tv_age"
  37. android:layout_width="wrap_content"
  38. android:layout_height="match_parent"
  39. android:gravity="center"
  40. android:text="年龄:"
  41. android:textColor="@color/black"
  42. android:textSize="17sp" />
  43. <EditText
  44. android:id="@+id/et_age"
  45. android:layout_width="match_parent"
  46. android:layout_height="match_parent"
  47. android:layout_marginBottom="3dp"
  48. android:layout_marginTop="3dp"
  49. android:layout_toRightOf="@+id/tv_age"
  50. android:background="@drawable/editext_selector"
  51. android:gravity="left|center"
  52. android:hint="请输入年龄"
  53. android:inputType="number"
  54. android:maxLength="2"
  55. android:textColor="@color/black"
  56. android:textSize="17sp" />
  57. </RelativeLayout>
  58. <RelativeLayout
  59. android:layout_width="match_parent"
  60. android:layout_height="40dp" >
  61. <TextView
  62. android:id="@+id/tv_height"
  63. android:layout_width="wrap_content"
  64. android:layout_height="match_parent"
  65. android:gravity="center"
  66. android:text="身高:"
  67. android:textColor="@color/black"
  68. android:textSize="17sp" />
  69. <EditText
  70. android:id="@+id/et_height"
  71. android:layout_width="match_parent"
  72. android:layout_height="match_parent"
  73. android:layout_marginBottom="3dp"
  74. android:layout_marginTop="3dp"
  75. android:layout_toRightOf="@+id/tv_height"
  76. android:background="@drawable/editext_selector"
  77. android:gravity="left|center"
  78. android:hint="请输入身高"
  79. android:inputType="number"
  80. android:maxLength="3"
  81. android:textColor="@color/black"
  82. android:textSize="17sp" />
  83. </RelativeLayout>
  84. <RelativeLayout
  85. android:layout_width="match_parent"
  86. android:layout_height="40dp" >
  87. <TextView
  88. android:id="@+id/tv_weight"
  89. android:layout_width="wrap_content"
  90. android:layout_height="match_parent"
  91. android:gravity="center"
  92. android:text="体重:"
  93. android:textColor="@color/black"
  94. android:textSize="17sp" />
  95. <EditText
  96. android:id="@+id/et_weight"
  97. android:layout_width="match_parent"
  98. android:layout_height="match_parent"
  99. android:layout_marginBottom="3dp"
  100. android:layout_marginTop="3dp"
  101. android:layout_toRightOf="@+id/tv_weight"
  102. android:background="@drawable/editext_selector"
  103. android:gravity="left|center"
  104. android:hint="请输入体重"
  105. android:inputType="numberDecimal"
  106. android:maxLength="5"
  107. android:textColor="@color/black"
  108. android:textSize="17sp" />
  109. </RelativeLayout>
  110. <RelativeLayout
  111. android:layout_width="match_parent"
  112. android:layout_height="40dp" >
  113. <CheckBox
  114. android:id="@+id/ck_married"
  115. android:layout_width="wrap_content"
  116. android:layout_height="match_parent"
  117. android:gravity="center"
  118. android:checked="false"
  119. android:text="已婚"
  120. android:textColor="@color/black"
  121. android:textSize="17sp" />
  122. </RelativeLayout>
  123. <Button
  124. android:id="@+id/btn_save"
  125. android:layout_width="match_parent"
  126. android:layout_height="wrap_content"
  127. android:text="保存到数据库"
  128. android:textColor="@color/black"
  129. android:textSize="17sp" />
  130. </LinearLayout>

activity_sqlite_readXML文件

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical" >
  5. <Button
  6. android:id="@+id/btn_delete"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="删除所有记录"
  10. android:textColor="@color/black"
  11. android:textSize="17sp" />
  12. <TextView
  13. android:id="@+id/tv_sqlite"
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content"
  16. android:paddingLeft="5dp"
  17. android:textColor="@color/black"
  18. android:textSize="17sp" />
  19. </LinearLayout>

三、优化记住密码功能

真正的记住密码功能应该是先输入手机号码,然后根据手机号码匹配保存的密码,一个手机号码对应一个密码,并支持根据手机号查找登录信息,从而同时记住多个手机号的密码 这是通过SQLite数据库可以实现这一点 后台保存密码和手机号 效果如下

 

 LoginSQLiteActivity类

  1. package com.example.chapter06;
  2. import android.annotation.SuppressLint;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7. import android.text.Editable;
  8. import android.text.TextWatcher;
  9. import android.view.View;
  10. import android.view.View.OnFocusChangeListener;
  11. import android.widget.Button;
  12. import android.widget.CheckBox;
  13. import android.widget.CompoundButton;
  14. import android.widget.EditText;
  15. import android.widget.RadioButton;
  16. import android.widget.RadioGroup;
  17. import android.widget.TextView;
  18. import android.widget.Toast;
  19. import androidx.appcompat.app.AppCompatActivity;
  20. import com.example.chapter06.bean.UserInfo;
  21. import com.example.chapter06.database.UserDBHelper;
  22. import com.example.chapter06.util.DateUtil;
  23. import com.example.chapter06.util.ViewUtil;
  24. import java.util.Random;
  25. @SuppressLint("DefaultLocale")
  26. public class LoginSQLiteActivity extends AppCompatActivity implements View.OnClickListener, OnFocusChangeListener {
  27. private RadioGroup rg_login; // 声明一个单选组对象
  28. private RadioButton rb_password; // 声明一个单选按钮对象
  29. private RadioButton rb_verifycode; // 声明一个单选按钮对象
  30. private EditText et_phone; // 声明一个编辑框对象
  31. private TextView tv_password; // 声明一个文本视图对象
  32. private EditText et_password; // 声明一个编辑框对象
  33. private Button btn_forget; // 声明一个按钮控件对象
  34. private CheckBox ck_remember; // 声明一个复选框对象
  35. private int mRequestCode = 0; // 跳转页面时的请求代码
  36. private boolean bRemember = false; // 是否记住密码
  37. private String mPassword = "111111"; // 默认密码
  38. private String mVerifyCode; // 验证码
  39. private UserDBHelper mHelper; // 声明一个用户数据库的帮助器对象
  40. @Override
  41. protected void onCreate(Bundle savedInstanceState) {
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.activity_login_sqlite);
  44. rg_login = findViewById(R.id.rg_login);
  45. rb_password = findViewById(R.id.rb_password);
  46. rb_verifycode = findViewById(R.id.rb_verifycode);
  47. et_phone = findViewById(R.id.et_phone);
  48. tv_password = findViewById(R.id.tv_password);
  49. et_password = findViewById(R.id.et_password);
  50. btn_forget = findViewById(R.id.btn_forget);
  51. ck_remember = findViewById(R.id.ck_remember);
  52. // 给rg_login设置单选监听器
  53. rg_login.setOnCheckedChangeListener(new RadioListener());
  54. // 给ck_remember设置勾选监听器
  55. ck_remember.setOnCheckedChangeListener(new CheckListener());
  56. // 给et_phone添加文本变更监听器
  57. et_phone.addTextChangedListener(new HideTextWatcher(et_phone, 11));
  58. // 给et_password添加文本变更监听器
  59. et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));
  60. btn_forget.setOnClickListener(this);
  61. findViewById(R.id.btn_login).setOnClickListener(this);
  62. // 给密码编辑框注册一个焦点变化监听器,一旦焦点发生变化,就触发监听器的onFocusChange方法
  63. et_password.setOnFocusChangeListener(this);
  64. }
  65. // 定义登录方式的单选监听器
  66. private class RadioListener implements RadioGroup.OnCheckedChangeListener {
  67. @Override
  68. public void onCheckedChanged(RadioGroup group, int checkedId) {
  69. if (checkedId == R.id.rb_password) { // 选择了密码登录
  70. tv_password.setText("登录密码:");
  71. et_password.setHint("请输入密码");
  72. btn_forget.setText("忘记密码");
  73. ck_remember.setVisibility(View.VISIBLE);
  74. } else if (checkedId == R.id.rb_verifycode) { // 选择了验证码登录
  75. tv_password.setText(" 验证码:");
  76. et_password.setHint("请输入验证码");
  77. btn_forget.setText("获取验证码");
  78. ck_remember.setVisibility(View.INVISIBLE);
  79. }
  80. }
  81. }
  82. // 定义是否记住密码的勾选监听器
  83. private class CheckListener implements CompoundButton.OnCheckedChangeListener {
  84. @Override
  85. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  86. if (buttonView.getId() == R.id.ck_remember) {
  87. bRemember = isChecked;
  88. }
  89. }
  90. }
  91. // 定义一个编辑框监听器,在输入文本达到指定长度时自动隐藏输入法
  92. private class HideTextWatcher implements TextWatcher {
  93. private EditText mView; // 声明一个编辑框对象
  94. private int mMaxLength; // 声明一个最大长度变量
  95. public HideTextWatcher(EditText v, int maxLength) {
  96. super();
  97. mView = v;
  98. mMaxLength = maxLength;
  99. }
  100. // 在编辑框的输入文本变化前触发
  101. public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
  102. // 在编辑框的输入文本变化时触发
  103. public void onTextChanged(CharSequence s, int start, int before, int count) {}
  104. // 在编辑框的输入文本变化后触发
  105. public void afterTextChanged(Editable s) {
  106. String str = s.toString(); // 获得已输入的文本字符串
  107. // 输入文本达到11位(如手机号码),或者达到6位(如登录密码)时关闭输入法
  108. if ((str.length() == 11 && mMaxLength == 11)
  109. || (str.length() == 6 && mMaxLength == 6)) {
  110. ViewUtil.hideOneInputMethod(LoginSQLiteActivity.this, mView); // 隐藏输入法软键盘
  111. }
  112. }
  113. }
  114. @Override
  115. public void onClick(View v) {
  116. String phone = et_phone.getText().toString();
  117. if (v.getId() == R.id.btn_forget) { // 点击了“忘记密码”按钮
  118. if (phone.length() < 11) { // 手机号码不足11
  119. Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
  120. return;
  121. }
  122. if (rb_password.isChecked()) { // 选择了密码方式校验,此时要跳到找回密码页面
  123. // 以下携带手机号码跳转到找回密码页面
  124. Intent intent = new Intent(this, LoginForgetActivity.class);
  125. intent.putExtra("phone", phone);
  126. startActivityForResult(intent, mRequestCode); // 携带意图返回上一个页面
  127. } else if (rb_verifycode.isChecked()) { // 选择了验证码方式校验,此时要生成六位随机数字验证码
  128. // 生成六位随机数字的验证码
  129. mVerifyCode = String.format("%06d", new Random().nextInt(999999));
  130. // 以下弹出提醒对话框,提示用户记住六位验证码数字
  131. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  132. builder.setTitle("请记住验证码");
  133. builder.setMessage("手机号" + phone + ",本次验证码是" + mVerifyCode + ",请输入验证码");
  134. builder.setPositiveButton("好的", null);
  135. AlertDialog alert = builder.create();
  136. alert.show(); // 显示提醒对话框
  137. }
  138. } else if (v.getId() == R.id.btn_login) { // 点击了“登录”按钮
  139. if (phone.length() < 11) { // 手机号码不足11
  140. Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
  141. return;
  142. }
  143. if (rb_password.isChecked()) { // 密码方式校验
  144. if (!et_password.getText().toString().equals(mPassword)) {
  145. Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
  146. } else { // 密码校验通过
  147. loginSuccess(); // 提示用户登录成功
  148. }
  149. } else if (rb_verifycode.isChecked()) { // 验证码方式校验
  150. if (!et_password.getText().toString().equals(mVerifyCode)) {
  151. Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
  152. } else { // 验证码校验通过
  153. loginSuccess(); // 提示用户登录成功
  154. }
  155. }
  156. }
  157. }
  158. // 从下一个页面携带参数返回当前页面时触发
  159. @Override
  160. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  161. super.onActivityResult(requestCode, resultCode, data);
  162. if (requestCode == mRequestCode && data != null) {
  163. // 用户密码已改为新密码,故更新密码变量
  164. mPassword = data.getStringExtra("new_password");
  165. }
  166. }
  167. // 从修改密码页面返回登录页面,要清空密码的输入框
  168. @Override
  169. protected void onRestart() {
  170. super.onRestart();
  171. et_password.setText("");
  172. }
  173. @Override
  174. protected void onResume() {
  175. super.onResume();
  176. mHelper = UserDBHelper.getInstance(this, 1); // 获得用户数据库帮助器的实例
  177. mHelper.openWriteLink(); // 恢复页面,则打开数据库连接
  178. }
  179. @Override
  180. protected void onPause() {
  181. super.onPause();
  182. mHelper.closeLink(); // 暂停页面,则关闭数据库连接
  183. }
  184. // 校验通过,登录成功
  185. private void loginSuccess() {
  186. String desc = String.format("您的手机号码是%s,恭喜你通过登录验证,点击“确定”按钮返回上个页面",
  187. et_phone.getText().toString());
  188. // 以下弹出提醒对话框,提示用户登录成功
  189. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  190. builder.setTitle("登录成功");
  191. builder.setMessage(desc);
  192. builder.setPositiveButton("确定返回", new DialogInterface.OnClickListener() {
  193. @Override
  194. public void onClick(DialogInterface dialog, int which) {
  195. finish(); // 结束当前的活动页面
  196. }
  197. });
  198. builder.setNegativeButton("我再看看", null);
  199. AlertDialog alert = builder.create();
  200. alert.show();
  201. // 如果勾选了“记住密码”,则把手机号码和密码保存为数据库的用户表记录
  202. if (bRemember) {
  203. UserInfo info = new UserInfo(); // 创建一个用户信息对象
  204. info.phone = et_phone.getText().toString();
  205. info.password = et_password.getText().toString();
  206. info.update_time = DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss");
  207. mHelper.insert(info); // 往用户数据库添加登录成功的用户信息
  208. }
  209. }
  210. // 焦点变更事件的处理方法,hasFocus表示当前控件是否获得焦点。
  211. // 为什么光标进入密码框事件不选onClick?因为要点两下才会触发onClick动作(第一下是切换焦点动作)
  212. @Override
  213. public void onFocusChange(View v, boolean hasFocus) {
  214. String phone = et_phone.getText().toString();
  215. // 判断是否是密码编辑框发生焦点变化
  216. if (v.getId() == R.id.et_password) {
  217. // 用户已输入手机号码,且密码框获得焦点
  218. if (phone.length() > 0 && hasFocus) {
  219. // 根据手机号码到数据库中查询用户记录
  220. UserInfo info = mHelper.queryByPhone(phone);
  221. if (info != null) {
  222. // 找到用户记录,则自动在密码框中填写该用户的密码
  223. et_password.setText(info.password);
  224. }
  225. }
  226. }
  227. }
  228. }

LoginForgetActivity类

  1. package com.example.chapter06;
  2. import android.annotation.SuppressLint;
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.EditText;
  9. import android.widget.Toast;
  10. import androidx.appcompat.app.AppCompatActivity;
  11. import java.util.Random;
  12. @SuppressLint("DefaultLocale")
  13. public class LoginForgetActivity extends AppCompatActivity implements View.OnClickListener {
  14. private EditText et_password_first; // 声明一个编辑框对象
  15. private EditText et_password_second; // 声明一个编辑框对象
  16. private EditText et_verifycode; // 声明一个编辑框对象
  17. private String mVerifyCode; // 验证码
  18. private String mPhone; // 手机号码
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_login_forget);
  23. // 从布局文件中获取名叫et_password_first的编辑框
  24. et_password_first = findViewById(R.id.et_password_first);
  25. // 从布局文件中获取名叫et_password_second的编辑框
  26. et_password_second = findViewById(R.id.et_password_second);
  27. // 从布局文件中获取名叫et_verifycode的编辑框
  28. et_verifycode = findViewById(R.id.et_verifycode);
  29. findViewById(R.id.btn_verifycode).setOnClickListener(this);
  30. findViewById(R.id.btn_confirm).setOnClickListener(this);
  31. // 从上一个页面获取要修改密码的手机号码
  32. mPhone = getIntent().getStringExtra("phone");
  33. }
  34. @Override
  35. public void onClick(View v) {
  36. if (v.getId() == R.id.btn_verifycode) { // 点击了“获取验证码”按钮
  37. if (mPhone == null || mPhone.length() < 11) {
  38. Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
  39. return;
  40. }
  41. // 生成六位随机数字的验证码
  42. mVerifyCode = String.format("%06d", new Random().nextInt(999999));
  43. // 以下弹出提醒对话框,提示用户记住六位验证码数字
  44. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  45. builder.setTitle("请记住验证码");
  46. builder.setMessage("手机号" + mPhone + ",本次验证码是" + mVerifyCode + ",请输入验证码");
  47. builder.setPositiveButton("好的", null);
  48. AlertDialog alert = builder.create();
  49. alert.show(); // 显示提醒对话框
  50. } else if (v.getId() == R.id.btn_confirm) { // 点击了“确定”按钮
  51. String password_first = et_password_first.getText().toString();
  52. String password_second = et_password_second.getText().toString();
  53. if (password_first.length() < 6 || password_second.length() < 6) {
  54. Toast.makeText(this, "请输入正确的新密码", Toast.LENGTH_SHORT).show();
  55. return;
  56. }
  57. if (!password_first.equals(password_second)) {
  58. Toast.makeText(this, "两次输入的新密码不一致", Toast.LENGTH_SHORT).show();
  59. return;
  60. }
  61. if (!et_verifycode.getText().toString().equals(mVerifyCode)) {
  62. Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
  63. } else {
  64. Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
  65. // 以下把修改好的新密码返回给上一个页面
  66. Intent intent = new Intent(); // 创建一个新意图
  67. intent.putExtra("new_password", password_first); // 存入新密码
  68. setResult(Activity.RESULT_OK, intent); // 携带意图返回上一个页面
  69. finish(); // 结束当前的活动页面
  70. }
  71. }
  72. }
  73. }

部分代码与XML文件省略...

创作不易 觉得有帮助请点赞关注收藏

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号