Android 使用Room操作SQLite数据库让其变得无比高效和简洁(教程一)

本文主要是介绍Android 使用Room操作SQLite数据库让其变得无比高效和简洁(教程一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站

前言:首先添加依赖和创建布局页面实现添加,更新,删除,清空这四个按钮,之后再去实现相应的功能。

一、首先在build.gradle里面添加相关的依赖

	def room_version = "2.3.0"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version"// optional - Test helperstestImplementation "androidx.room:room-testing:$room_version"// optional - Paging 3 Integrationimplementation "androidx.room:room-paging:2.4.0-beta01"

二、布局页面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"android:orientation="vertical"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"><TextViewandroid:id="@+id/tv_text"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:gravity="center"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_insert"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="添加" /><Buttonandroid:id="@+id/btn_update"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="50dp"android:text="更新" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:gravity="center"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_clear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="清空" /><Buttonandroid:id="@+id/btn_delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="50dp"android:text="删除" /></LinearLayout></LinearLayout></LinearLayout>

三、创建实体类Word,具体注释都已给出

@Entity
public class Word {//标注为主键 并且自动生成@PrimaryKey(autoGenerate = true)public int id;//ColumnInfo标注列的名称 如果不标注则以变量名 为列名@ColumnInfo(name="english_word")public String word;@ColumnInfo(name = "chinese_meaning")public String chineseMeaning;public Word(String word, String chineseMeaning) {this.word = word;this.chineseMeaning = chineseMeaning;}public void setId(int id) {this.id = id;}public int getId() {return id;}public String getWord() {return word;}public void setWord(String word) {this.word = word;}public String getChineseMeaning() {return chineseMeaning;}public void setChineseMeaning(String chineseMeaning) {this.chineseMeaning = chineseMeaning;}
}

四、创建一个访问数据库操作的接口WordDao,具体的增删改查功能,都要在这个接口里面声明

//访问数据库操作的接口
@Dao  //Database access Object
public interface WordDao {//添加数据@Insertvoid insertWords(Word...words);@Delete//根据条件删除数据void deleteWords(Word...words);//删除所有数据@Query("DELETE FROM WORD")void deleteAllWords();//更新数据@Updatevoid updateWords(Word...words);//查询返回所有数据@Query("SELECT * FROM WORD ORDER BY ID DESC")List<Word> getAllWords();
}

五、创建一个抽象类WordDataBase,如果有多个entities,则应该写多个Dao

// 参数1:实体类  参数2:数据库版本号 参数3:禁止将数据库架构导入到给定的文件夹中
@Database(entities = {Word.class},version = 1,exportSchema = false)
public abstract class WordDataBase extends RoomDatabase {public abstract WordDao getWordDao();
}

六、所有准备工作完成后,在Activity文件中,进行相应功能的实现:

public class MainActivity extends AppCompatActivity {private WordDataBase wordDataBase;private WordDao wordDao;private Button btn_insert, btn_clear, btn_update, btn_delete;private TextView tv_text;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);wordDataBase = Room.databaseBuilder(this, WordDataBase.class, "word_database").allowMainThreadQueries().build();wordDao = wordDataBase.getWordDao();btn_insert = findViewById(R.id.btn_insert);btn_clear = findViewById(R.id.btn_clear);btn_update = findViewById(R.id.btn_update);btn_delete = findViewById(R.id.btn_delete);tv_text = findViewById(R.id.tv_text);updateView();btn_insert.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Word word1 = new Word("Hello", "你好!");Word word2 = new Word("World", "世界!");wordDao.insertWords(word1, word2);updateView();}});btn_clear.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {wordDao.deleteAllWords();updateView();}});btn_update.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Word word = new Word("Hi", "你好啊");word.setId(10);wordDao.updateWords(word);updateView();}});btn_delete.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Word word = new Word("Hi", "你好啊");word.setId(10);wordDao.deleteWords(word);updateView();}});}private void updateView() {List<Word> list = wordDao.getAllWords();String text = "";for (int i = 0; i < list.size(); i++) {Word word = list.get(i);text += word.getId() + ":" + word.getWord() + "=" + word.getChineseMeaning() + "\n";}tv_text.setText(text);}}

效果图:
在这里插入图片描述
这只是一个简单的实现效果,后续会陆续完善~
相关文章持续更新中

Android 使用Room操作SQLite数据库让其变得无比高效和简洁(完善)

Android使用Room操作SQLite数据库让其变得无比高效和简洁(进一步完善用RecyclerView显示数据库中的数据)

Android 使用Room操作数据库进行数据库版本的升级和迁移

这篇关于Android 使用Room操作SQLite数据库让其变得无比高效和简洁(教程一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/670203

相关文章

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

Python 中的 with open文件操作的最佳实践

《Python中的withopen文件操作的最佳实践》在Python中,withopen()提供了一个简洁而安全的方式来处理文件操作,它不仅能确保文件在操作完成后自动关闭,还能处理文件操作中的异... 目录什么是 with open()?为什么使用 with open()?使用 with open() 进行

关于pandas的read_csv方法使用解读

《关于pandas的read_csv方法使用解读》:本文主要介绍关于pandas的read_csv方法使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录pandas的read_csv方法解读read_csv中的参数基本参数通用解析参数空值处理相关参数时间处理相关

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳