做网站竞品分析,国内个人网站搭建,建筑公司企业理念,wordpress默认登录地址本节介绍Android的数据库存储方式--SQLite的使用方法#xff0c;包括#xff1a;SQLite用到了哪些SQL语法#xff0c;如何使用数据库管理操纵SQLitem#xff0c;如何使用数据库帮助器简化数据库操作#xff0c;以及如何利用SQLite改进登录页面的记住密码功能。
6.2.1 SQ…本节介绍Android的数据库存储方式--SQLite的使用方法包括SQLite用到了哪些SQL语法如何使用数据库管理操纵SQLitem如何使用数据库帮助器简化数据库操作以及如何利用SQLite改进登录页面的记住密码功能。
6.2.1 SQL的基本语法
SQL本质上是一种编程语言它的学名叫做“结构化查询语言”全称为Structured Query Language简称SQL。不过SQL语言并非通用的编程语言它专用于数据库的访问和处理更像是一种操作命令所以常说SQL语句而不说SQL代码。标准的SQL语句分为3类数据定义数据操纵和数据控制。但不同的数据库往往有自己的实现。
SQLite是一种小巧的嵌入式数据库使用方便开发简单。如同MYSQLOracle那样SQLite也采用SQL语句管理数据由于它属于轻型数据库不涉及复杂的数据控制操作因此App开发只用到数据定义和数据操纵两类SQL语句。此外SQLite的SQL语法与通用的SQL语法略有不同接下来介绍的两类SQL语法全部基于SQLite。 1. 数据定义语言 数据定义语言全称Data Definition Language简称DDL描述了怎样变更数据实体的框架结构。就SQLite而言DDL语言主要包括3种操作创建表格删除表格修改表结构分别说明如下。 1创建表格 表格的创建动作由create命令完成格式为“CREATE TABLE IF NOT EXISTS 表格名称以逗号分隔的名字段定义”。以用户信息表为例它的建表语句如下
CREATE TABLE IF NOT EXISTS user_info(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name VARCHAR NOT NULL, age INTEGER NOT NULL,height LONG NOT NULL, weight FLOAT NOT NULL,married INTEGER NOT NULL, update_time VARCHAR NOT NULL);
上面的SQL语法与其他数据库的SQL语法有所出入相关的注意点说明如下
① SQL语句不区分大小写无论是create与table这类关键词还是表格名称字段名称都不区分大小写。唯一区分大小写的是被单引号括起来的字符串值。
② 为避免重复建表应加上IF NOT EXISTS关键词例如CREATE TABLE IF NOT EXISTS 表格名称 ▪▪▪▪
③ SQLite支持整型INTEGER长整型LONG字符串VARCHAR浮点型FLOAT但不支持布尔类型。布尔类型的数据要使用整型保存如果直接保存布尔数据在入库时SQLite会自动将它转为0或1其中0表示false1表示true。
④ 建表时需要唯一标识字段它的字段名为_id。创建新表都要加上该字段定义例如_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL。 2删除表格 表格的删除动作由drop命令完成格式为“DROP TABLE IF EXISTS 表格名称”。下面是删除用户信息的SQL语句例子
DROP TABLE IF EXISTS user_info; 3修改表结构 表格的修改动作由alter命令完成格式为“ALTER TABLE 表格名称 修改操作”。不过SQLite只支持增加字段不支持修改字段也不支持删除字段。对于字段增加操作需要在alter之后补充add命令具体格式如“ALTER TABLE 表格名称 ADD COLUMN 字段名称 字段类型;”。下面是给用户信息表增加手机号字段的SQL语句例子
ALTER_TABLE user_info ADD COLUMN phone VARCHAR;
2. 数据操纵语言
数据操纵语言全称Data Manipulation Language简称DML描述了怎样处理数据实体的内部记录。表格记录的操作类型包括添加删除修改查询4类分别说明如下
1添加记录 记录的添加动作由insert命令完成格式为“INSERT INTO 表格名称以逗号分隔的字段名列表VALUES以逗号分隔的字段值列表;”。下面是往用户信息表插入一条记录的SQL语句例子
INSERT INTO user_info (name,age,height,weight,married,update_time)
VALUES (张三,20,170,50,0,20200504);
2删除记录 记录的删除动作由delete命令完成格式为“DELETE FROM 表格名称 WHERE 查询条件;”其中查询条件的表达式形如“字段名字段值”多个字段的条件交集通过“AND”连接条件并集通过“OR”连接。下面是从用户信息表删除指定记录的SQL语句例子
DELETE FROM user_info WHERE name张三;
3修改记录 记录的修改动作由update命令完成格式为“UPDATE 表格名称 SET 字段名字段值 WHERE 查询条件;”。下面是对用户信息表更新指定记录的SQL语句例子
UPDATE user_info SET married1 WHERE name张三;
4查询记录 记录的查询动作由select命令完成格式为“SELECT 以逗号分隔的字段名列表 FROM 表格名称 WHERE 查询条件;”。如果字段名列表填星号*则表示查询该表的所有字段。下面是从用户信息表查询指定记录的SQL语句例子
SELECT*FROM user_info ORDER BY age ASC;
6.2.2 数据库管理器 SQLiteDatabase SQL语句毕竟只是SQL命令若要在Java代码中操纵SQLite还需专门的工具类。SQLiteDatabase便是Android提供的SQLite数据库管理器开发者可以在活动页面代码中调用openOrCreateDatabase方法获得数据库实例参考代码如下 SQLiteDatabase db openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE,null);String desc String.format(数据库%s创建%s, db.getPath(), (db!null)?成功:失败);tv_database.setText(desc); 完整代码如下
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationverticaltools:context.DatabaseActivityLinearLayoutandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:orientationhorizontalButtonandroid:idid/btn_database_createandroid:layout_width0dpandroid:layout_heightwrap_contentandroid:layout_weight1android:text创建数据库android:textColorcolor/blackandroid:textSize17sp /Buttonandroid:idid/btn_database_deleteandroid:layout_width0dpandroid:layout_heightwrap_contentandroid:layout_weight1android:text删除数据库android:textColorcolor/blackandroid:textSize17sp //LinearLayoutTextViewandroid:idid/tv_databaseandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:paddingLeft5dpandroid:textColorcolor/blackandroid:textSize17sp //LinearLayout
package com.example.datastorage;import androidx.appcompat.app.AppCompatActivity;import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;public class DatabaseActivity extends AppCompatActivity implements View.OnClickListener {private TextView tv_database; // 声明一个文本视图对象private String mDatabaseName;// 包含完整路径的数据库名称Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_database);tv_databasefindViewById(R.id.tv_database);findViewById(R.id.btn_database_create).setOnClickListener(this);findViewById(R.id.btn_database_delete).setOnClickListener(this);// 生成一个测试数据库的完整路径mDatabaseNamegetFilesDir()/test.db;}Overridepublic void onClick(View view) {if (view.getId()R.id.btn_database_create){// 创建或打开数据库。数据库如果不存在就创建它如果存在就打开它SQLiteDatabase db openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE,null);String desc String.format(数据库%s创建%s, db.getPath(), (db!null)?成功:失败);tv_database.setText(desc);} else if (view.getId()R.id.btn_database_delete) {boolean result deleteDatabase(mDatabaseName);// 删除数据库String desc String.format(数据库%s删除%s, mDatabaseName, result?成功:失败);tv_database.setText(desc);}}
} 首次运行测试App调用openOrCreateDatabase方法会自动创建数据库并返回该数据库的管理器实例创建结果如图所示。 获得数据库实例之后就能对该数据库开展各项操作了。数据库管理器SQLiteDatabase提供了若干操作数据表的API常用的方法有3类列举如下 1. 管理类用于数据库层面的操作 ● openDatabase打开指定路径的数据库。 ● isOpen判断数据库是否已打开。 ● close关闭数据库。 ● getVersion获取数据库的版本号。 ● setVersion设置数据库的版本号。 2. 事务类用于事务层面的操作 ● beginTransaction开始事务。 ● setTransactionSuccessful设置事务的成功标志。 ● endTransaction结束事务。执行本方法时系统会判断之前是否调用了 setTransactionSuccessful方法如果之前已调用该方法就提交事务如果没有调用该方法就 回滚事务。 3. 数据处理类用于数据表层面的操作 ● execSQL执行拼接好的SQL控制语句。一般用于建表删表变更表结构。 ● delete删除符合条件的记录。 ● update更新符合条件的记录信息。 ● insert插入一条记录。 ● query执行查询操作并返回结果集的游标。 ● rawQuery执行拼接好的SQL查询语句并返回结果集的游标。 在实际开发中经常用到的是查询语句建议写好查询操作的select语句再调用rawQuery方法执行查询语句。
6.2.3 数据库帮助器 SQLiteOpenHelper 由于SQLiteDatabase存在局限性一不小心就会重复打开数据库处理数据库的升级也不方便因此Android提供了数据库帮助器SQLiteOpenHelper帮助开发者合理使用SQLite。 SQLiteOpenHelper的具体使用步骤如下
01 新建一个继承SQLiteOpenHelper的数据库操作类按提示重写onCreate和onUpgrade两个方 法。其中onCreate方法只在第一次打开数据库时执行在此可以创建表结构而onUpgrade 方法在数据库版本升高时执行在此可以根据新旧版本号变更表结构。
02 为保证数据库的安全使用需要封装几个必要方法包括获取单例对象打开数据库连接关 闭数据库连接说明如下 ● 获取单例对象确保在App运行过程中数据库只会打开一次避免重复打开引起错误。 ● 打开数据库连接SQLite有锁机制即读锁和写锁的处理故而数据库连接也分两种读 连接可调用getReadableDatabase方法获得写连接可调用getWritableDatabase方法获得。 ● 关闭数据库连接数据库操作完毕调用数据库实例的close方法关闭连接。
03 提供对表记录增加删除修改查询的操作方法。 能被SQLite直接使用的数据结构是ContentValues类它类似于映射Map也提供了put和get方法存取键值对。区别之处在于ContentValues的键只能是字符串不能是其他类型。ContentValues主要用于增加记录和更新记录对应数据库的insert和update方法。 记录的查询操作用到了游标类Cursor调用query和rawQuery方法返回的都是Cursor对象若要获取全部的查询结果则需要根据游标的指示一条一条遍历结果集合。Cursor的常用方法可分为3类说明如下 1. 游标控制类方法用于指定游标的状态 ● close关闭游标。 ● isClosed判断游标是否关闭。 ● isFirst判断游标是否在开头。 ● isLast判断游标是否在末尾。 2. 游标移动类方法把游标移动到指定位置 ● moveToFirst移动游标到开头。 ● moveToLast移动游标到末尾。 ● moveToNext移动游标到下一条记录。 ● moveToPrevious移动游标到上一条记录。 ● move往后移动游标若干条记录。 ● moveToPosition移动游标到指定位置的记录。 3. 获取记录类方法可获取记录的数量类型以及取值 ● getCount获取结果记录的数量。 ● getInt获取指定字段的整型值。 ● getLong获取指定字段的长整数型值。 ● getFloat获取指定字段的浮点数值。 ● getString获取指定字段的字符串值。 ● getType获取指定字段的字段类型。 鉴于数据库操作的特殊性不方便单独演示某个功能接下来从创建数据库开始介绍完整演示一下数据库的读写操作。用户注册信息的演示页面包括两个分别是记录保存页面和记录读取页面其中记录保存页面通过insert方法向数据库添加用户信息完整代码如下
package com.example.datastorage;public class UserInfo {public long rowid; // 行号public int xuhao; // 序号public String name; // 姓名public int age; // 年龄public long height; // 身高public float weight; // 体重public boolean married; // 婚否public String update_time; // 更新时间public String phone; // 手机号public String password; // 密码public UserInfo() {rowid 0L;xuhao 0;name ;age 0;height 0L;weight 0.0f;married false;update_time ;phone ;password ;}
}
package com.example.datastorage;import static android.provider.SyncStateContract.Helpers.update;
import static androidx.core.content.ContentResolverCompat.query;import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;import java.util.ArrayList;
import java.util.List;public class UserDBHelper extends SQLiteOpenHelper {private static final String TAG UserDBHelper;private static final String DB_NAME user.db; // 数据库的名称private static final int DB_VERSION 1; // 数据库的版本号private static UserDBHelper mHelper null; // 数据库帮助器的实例private SQLiteDatabase mDB null; // 数据库的实例public static final String TABLE_NAME user_info; // 表的名称private UserDBHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);}private UserDBHelper(Context context, int version) {super(context, DB_NAME, null, version);}// 利用单例模式获取数据库帮助器的唯一实例public static UserDBHelper getInstance(Context context, int version) {if (version 0 mHelper null) {mHelper new UserDBHelper(context, version);} else if (mHelper null) {mHelper new UserDBHelper(context);}return mHelper;}// 打开数据库的读连接public SQLiteDatabase openReadLink() {if (mDB null || !mDB.isOpen()) {mDB mHelper.getReadableDatabase();}return mDB;}// 打开数据库的写连接public SQLiteDatabase openWriteLink() {if (mDB null || !mDB.isOpen()) {mDB mHelper.getWritableDatabase();}return mDB;}// 关闭数据库连接public void closeLink() {if (mDB ! null mDB.isOpen()) {mDB.close();mDB null;}}// 创建数据库执行建表语句Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {Log.d(TAG, onCreate);String drop_sql DROP TABLE IF EXISTS TABLE_NAME ;;Log.d(TAG, drop_sql: drop_sql);sqLiteDatabase.execSQL(drop_sql);String create_sql CREATE TABLE IF NOT EXISTS TABLE_NAME ( _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR NOT NULL, age INTEGER NOT NULL, height INTEGER NOT NULL, weight FLOAT NOT NULL, married INTEGER NOT NULL, update_time VARCHAR NOT NULL//演示数据库升级时要先把下面这行注释 ,phone VARCHAR ,password VARCHAR );;Log.d(TAG, create_sql: create_sql);sqLiteDatabase.execSQL(create_sql); // 执行完整的SQL语句}// 升级数据库执行表结构变更语句Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {Log.d(TAG, onUpgrade oldVersion i , newVersion i1);if (i1 1) {//Android的ALTER命令不支持一次添加多列只能分多次添加String alter_sql ALTER TABLE TABLE_NAME ADD COLUMN phone VARCHAR;;Log.d(TAG, alter_sql: alter_sql);sqLiteDatabase.execSQL(alter_sql);alter_sql ALTER TABLE TABLE_NAME ADD COLUMN password VARCHAR;;Log.d(TAG, alter_sql: alter_sql);sqLiteDatabase.execSQL(alter_sql); // 执行完整的SQL语句}}// 根据指定条件删除表记录public int delete(String condition) {// 执行删除记录动作该语句返回删除记录的数目return mDB.delete(TABLE_NAME, condition, null);}// 删除该表的所有记录public int deleteAll() {// 执行删除记录动作该语句返回删除记录的数目return mDB.delete(TABLE_NAME, 11, null);}// 往该表添加一条记录public long insert(UserInfo info) {ListUserInfo infoList new ArrayListUserInfo();infoList.add(info);return insert(infoList);}// 往该表添加多条记录public long insert(ListUserInfo infoList) {long result -1;for (int i 0; i infoList.size(); i) {UserInfo info infoList.get(i);ListUserInfo tempList new ArrayListUserInfo();// 如果存在同名记录则更新记录// 注意条件语句的等号后面要用单引号括起来if (info.name ! null info.name.length() 0) {String condition String.format(name%s, info.name);tempList query(condition);if (tempList.size() 0) {update(info, condition);result tempList.get(0).rowid;continue;}}// 如果存在同样的手机号码则更新记录if (info.phone ! null info.phone.length() 0) {String condition String.format(phone%s, info.phone);tempList query(condition);if (tempList.size() 0) {update(info, condition);result tempList.get(0).rowid;continue;}}// 不存在唯一性重复的记录则插入新记录ContentValues cv new ContentValues();cv.put(name, info.name);cv.put(age, info.age);cv.put(height, info.height);cv.put(weight, info.weight);cv.put(married, info.married);cv.put(update_time, info.update_time);cv.put(phone, info.phone);cv.put(password, info.password);// 执行插入记录动作该语句返回插入记录的行号result mDB.insert(TABLE_NAME, , cv);if (result -1) { // 添加成功则返回行号添加失败则返回-1return result;}}return result;}// 根据条件更新指定的表记录public int update(UserInfo info, String condition) {ContentValues cv new ContentValues();cv.put(name, info.name);cv.put(age, info.age);cv.put(height, info.height);cv.put(weight, info.weight);cv.put(married, info.married);cv.put(update_time, info.update_time);cv.put(phone, info.phone);cv.put(password, info.password);// 执行更新记录动作该语句返回更新的记录数量return mDB.update(TABLE_NAME, cv, condition, null);}public int update(UserInfo info) {// 执行更新记录动作该语句返回更新的记录数量return update(info, rowid info.rowid);}// 根据指定条件查询记录并返回结果数据列表public ListUserInfo query(String condition) {String sql String.format(select rowid,_id,name,age,height, weight,married,update_time,phone,password from %s where %s;, TABLE_NAME, condition);Log.d(TAG, query sql: sql);ListUserInfo infoList new ArrayListUserInfo();// 执行记录查询动作该语句返回结果集的游标Cursor cursor mDB.rawQuery(sql, null);// 循环取出游标指向的每条记录while (cursor.moveToNext()) {UserInfo info new UserInfo();info.rowid cursor.getLong(0); // 取出长整型数info.xuhao cursor.getInt(1); // 取出整型数info.name cursor.getString(2); // 取出字符串info.age cursor.getInt(3); // 取出整型数info.height cursor.getLong(4); // 取出长整型数info.weight cursor.getFloat(5); // 取出浮点数//SQLite没有布尔型用0表示false用1表示trueinfo.married (cursor.getInt(6) 0) ? false : true;info.update_time cursor.getString(7); // 取出字符串info.phone cursor.getString(8); // 取出字符串info.password cursor.getString(9); // 取出字符串infoList.add(info);}cursor.close(); // 查询完毕关闭数据库游标return infoList;}// 根据手机号码查询指定记录public UserInfo queryByPhone(String phone) {UserInfo info null;ListUserInfo infoList query(String.format(phone%s, phone));if (infoList.size() 0) { // 存在该号码的登录信息info infoList.get(0);}return info;}}
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationverticalandroid:padding5dptools:context.SQLiteWriteActivityRelativeLayoutandroid:layout_widthmatch_parentandroid:layout_height56dpTextViewandroid:idid/tv_nameandroid:layout_widthwrap_contentandroid:layout_heightmatch_parentandroid:text姓名android:gravitycenterandroid:textSize17sp/EditTextandroid:idid/et_nameandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:layout_marginBottom3dpandroid:layout_marginTop3dpandroid:layout_toRightOfid/tv_nameandroid:backgrounddrawable/editext_selectorandroid:gravityleft|centerandroid:hint请输入姓名android:inputTypetextandroid:maxLength12android:textColorcolor/blackandroid:textSize17sp //RelativeLayoutRelativeLayoutandroid:layout_widthmatch_parentandroid:layout_height40dp TextViewandroid:idid/tv_ageandroid:layout_widthwrap_contentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:text年龄android:textColorcolor/blackandroid:textSize17sp /EditTextandroid:idid/et_ageandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:layout_marginBottom3dpandroid:layout_marginTop3dpandroid:layout_toRightOfid/tv_ageandroid:backgrounddrawable/editext_selectorandroid:gravityleft|centerandroid:hint请输入年龄android:inputTypenumberandroid:maxLength2android:textColorcolor/blackandroid:textSize17sp //RelativeLayoutRelativeLayoutandroid:layout_widthmatch_parentandroid:layout_height40dp TextViewandroid:idid/tv_heightandroid:layout_widthwrap_contentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:text身高android:textColorcolor/blackandroid:textSize17sp /EditTextandroid:idid/et_heightandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:layout_marginBottom3dpandroid:layout_marginTop3dpandroid:layout_toRightOfid/tv_heightandroid:backgrounddrawable/editext_selectorandroid:gravityleft|centerandroid:hint请输入身高android:inputTypenumberandroid:maxLength3android:textColorcolor/blackandroid:textSize17sp //RelativeLayoutRelativeLayoutandroid:layout_widthmatch_parentandroid:layout_height40dp TextViewandroid:idid/tv_weightandroid:layout_widthwrap_contentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:text体重android:textColorcolor/blackandroid:textSize17sp /EditTextandroid:idid/et_weightandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:layout_marginBottom3dpandroid:layout_marginTop3dpandroid:layout_toRightOfid/tv_weightandroid:backgrounddrawable/editext_selectorandroid:gravityleft|centerandroid:hint请输入体重android:inputTypenumberDecimalandroid:maxLength5android:textColorcolor/blackandroid:textSize17sp //RelativeLayoutRelativeLayoutandroid:layout_widthmatch_parentandroid:layout_height40dp CheckBoxandroid:idid/ck_marriedandroid:layout_widthwrap_contentandroid:layout_heightmatch_parentandroid:gravitycenterandroid:checkedfalseandroid:text已婚android:textColorcolor/blackandroid:textSize17sp //RelativeLayoutButtonandroid:idid/btn_saveandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:text保存到数据库android:textColorcolor/blackandroid:textSize17sp /Buttonandroid:idid/btn_jumpandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:text跳转到数据库android:textColorcolor/blackandroid:textSize17sp /
/LinearLayout
package com.example.datastorage;import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;public class SQLiteWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {private UserDBHelper mHelper; // 声明一个用户数据库帮助器的对象private EditText et_name; // 声明一个编辑框对象private EditText et_age; // 声明一个编辑框对象private EditText et_height; // 声明一个编辑框对象private EditText et_weight; // 声明一个编辑框对象private boolean isMarried false;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_sqlite_write);et_name findViewById(R.id.et_name);et_age findViewById(R.id.et_age);et_height findViewById(R.id.et_height);et_weight findViewById(R.id.et_weight);CheckBox ck_married findViewById(R.id.ck_married);ck_married.setOnCheckedChangeListener(this);findViewById(R.id.btn_save).setOnClickListener(this);findViewById(R.id.btn_jump).setOnClickListener(this);}Overrideprotected void onStart() {super.onStart();// 获得数据库帮助器的实例mHelper UserDBHelper.getInstance(this,1);mHelper.openWriteLink();// 打开数据库帮助器的写连接}Overrideprotected void onStop() {super.onStop();mHelper.closeLink();// 关闭数据库连接}Overridepublic void onClick(View view) {if (view.getId()R.id.btn_save){String name et_name.getText().toString();String age et_age.getText().toString();String height et_height.getText().toString();String weight et_weight.getText().toString();if (TextUtils.isEmpty(name)) {Toast.makeText(this, 请先填写姓名,Toast.LENGTH_LONG).show();return;} else if (TextUtils.isEmpty(age)) {Toast.makeText(this, 请先填写年龄,Toast.LENGTH_LONG).show();return;} else if (TextUtils.isEmpty(height)) {Toast.makeText(this, 请先填写身高,Toast.LENGTH_LONG).show();return;} else if (TextUtils.isEmpty(weight)) {Toast.makeText(this, 请先填写体重,Toast.LENGTH_LONG).show();return;}// 以下声明一个用户信息对象并填写它的各字段值UserInfo info new UserInfo();info.name name;info.age Integer.parseInt(age);info.weight Float.parseFloat(weight);info.married isMarried;info.update_time DateUtil.getNowDateTime(yyyy-MM-dd HH:mm:ss);mHelper.insert(info);// 执行数据库帮助器的插入操作Toast.makeText(this, 数据已写入SQLite数据库,Toast.LENGTH_LONG).show();} else if (view.getId()R.id.btn_jump) {Intent intent new Intent(this, SQLiteReadActivity.class);startActivity(intent);}}Overridepublic void onCheckedChanged(CompoundButton compoundButton, boolean b) {isMarried b;}
}
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationverticaltools:context.SQLiteReadActivityButtonandroid:idid/btn_deleteandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:text删除所有记录android:textSize17sp/TextViewandroid:idid/tv_sqliteandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:paddingLeft5dpandroid:textColorcolor/blackandroid:textSize17sp //LinearLayout
package com.example.datastorage;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;import java.util.List;public class SQLiteReadActivity extends AppCompatActivity implements View.OnClickListener {private UserDBHelper mHelper; // 声明一个用户数据库帮助器的对象private TextView tv_sqlite; // 声明一个文本视图对象Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_sqlite_read);tv_sqlite findViewById(R.id.tv_sqlite);findViewById(R.id.btn_delete).setOnClickListener(this);}Overrideprotected void onStart() {super.onStart();// 获得数据库帮助器的实例mHelper UserDBHelper.getInstance(this, 1);mHelper.openReadLink(); // 打开数据库帮助器的读连接readSQLite(); // 读取数据库中保存的所有用户记录}Overrideprotected void onStop() {super.onStop();mHelper.closeLink(); // 关闭数据库连接}// 读取数据库中保存的所有用户记录private void readSQLite() {if (mHelper null) {Toast.makeText(this, 数据库连接为空, Toast.LENGTH_SHORT).show();return;}// 执行数据库帮助器的查询操作ListUserInfo userList mHelper.query(11);String desc String.format(数据库查询到%d条记录详情如下, userList.size());for (int i 0; i userList.size(); i) {UserInfo info userList.get(i);desc String.format(%s\n第%d条记录信息如下, desc, i 1);desc String.format(%s\n 姓名为%s, desc, info.name);desc String.format(%s\n 年龄为%d, desc, info.age);desc String.format(%s\n 身高为%d, desc, info.height);desc String.format(%s\n 体重为%f, desc, info.weight);desc String.format(%s\n 婚否为%b, desc, info.married);desc String.format(%s\n 更新时间为%s, desc, info.update_time);}if (userList.size() 0) {desc 数据库查询到的记录为空;}tv_sqlite.setText(desc);}Overridepublic void onClick(View view) {if (view.getId() R.id.btn_delete) {mHelper.closeLink(); // 关闭数据库连接mHelper.openWriteLink(); // 打开数据库帮助器的写连接mHelper.deleteAll(); // 删除所有记录mHelper.closeLink(); // 关闭数据库连接mHelper.openReadLink(); // 打开数据库帮助器的读连接readSQLite(); // 读取数据库中保存的所有用户记录Toast.makeText(this, 已删除所有记录, Toast.LENGTH_SHORT).show();}}
}
运行测试App,先打开记录保存页面依次录入信息并将两个用户的注册信息保存至数据库如图所示。 6.2.4 优化记住密码功能