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 helpers
    testImplementation "androidx.room:room-testing:$room_version"
    // optional - Paging 3 Integration
    implementation "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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <TextView
            android:id="@+id/tv_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal">
            <Button
                android:id="@+id/btn_insert"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="添加" />
            <Button
                android:id="@+id/btn_update"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="50dp"
                android:text="更新" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal">
            <Button
                android:id="@+id/btn_clear"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="清空" />
            <Button
                android: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 {
    //添加数据
    @Insert
    void insertWords(Word...words);
    @Delete
    //根据条件删除数据
    void deleteWords(Word...words);
    //删除所有数据
    @Query("DELETE FROM WORD")
    void deleteAllWords();
    //更新数据
    @Update
    void 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;
    @Override
    protected 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() {
            @Override
            public 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() {
            @Override
            public void onClick(View view) {
                wordDao.deleteAllWords();
                updateView();
            }
        });
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Word word = new Word("Hi", "你好啊");
                word.setId(10);
                wordDao.updateWords(word);
                updateView();
            }
        });
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public 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操作数据库进行数据库版本的升级和迁移


目录
相关文章
|
2月前
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
407 15
|
3月前
|
存储 SQL 数据库
数据库知识:了解SQLite或其他移动端数据库的使用
【10月更文挑战第22天】本文介绍了SQLite在移动应用开发中的应用,包括其优势、如何在Android中集成SQLite、基本的数据库操作(增删改查)、并发访问和事务处理等。通过示例代码,帮助开发者更好地理解和使用SQLite。此外,还提到了其他移动端数据库的选择。
79 8
|
4月前
|
Web App开发 SQL 数据库
使用 Python 解析火狐浏览器的 SQLite3 数据库
本文介绍如何使用 Python 解析火狐浏览器的 SQLite3 数据库,包括书签、历史记录和下载记录等。通过安装 Python 和 SQLite3,定位火狐数据库文件路径,编写 Python 脚本连接数据库并执行 SQL 查询,最终输出最近访问的网站历史记录。
77 4
|
4月前
|
存储 关系型数据库 数据库
轻量级数据库的利器:Python 及其内置 SQLite 简介
轻量级数据库的利器:Python 及其内置 SQLite 简介
106 3
|
4月前
|
应用服务中间件 PHP Apache
PbootCMS提示错误信息“未检测到您服务器环境的sqlite3数据库扩展...”
PbootCMS提示错误信息“未检测到您服务器环境的sqlite3数据库扩展...”
|
5月前
|
数据库 数据库管理
qt对sqlite数据库多线程的操作
本文总结了在Qt中进行SQLite数据库多线程操作时应注意的四个关键问题,包括数据库驱动加载、加锁、数据库的打开与关闭,以及QsqlQuery变量的使用。
324 1
|
4月前
|
存储 缓存 关系型数据库
sqlite 数据库 介绍
sqlite 数据库 介绍
95 0
|
1月前
|
关系型数据库 MySQL 数据库连接
数据库连接工具连接mysql提示:“Host ‘172.23.0.1‘ is not allowed to connect to this MySQL server“
docker-compose部署mysql8服务后,连接时提示不允许连接问题解决
|
22天前
|
关系型数据库 MySQL 数据库
Docker Compose V2 安装常用数据库MySQL+Mongo
以上内容涵盖了使用 Docker Compose 安装和管理 MySQL 和 MongoDB 的详细步骤,希望对您有所帮助。
122 42
|
13天前
|
关系型数据库 MySQL 网络安全
如何排查和解决PHP连接数据库MYSQL失败写锁的问题
通过本文的介绍,您可以系统地了解如何排查和解决PHP连接MySQL数据库失败及写锁问题。通过检查配置、确保服务启动、调整防火墙设置和用户权限,以及识别和解决长时间运行的事务和死锁问题,可以有效地保障应用的稳定运行。
67 25

热门文章

最新文章

  • 1
    android FragmentManager 删除所有Fragment 重建
    15
  • 2
    Android实战经验之Kotlin中快速实现MVI架构
    21
  • 3
    即时通讯安全篇(一):正确地理解和使用Android端加密算法
    24
  • 4
    escrcpy:【技术党必看】Android开发,Escrcpy 让你无线投屏新体验!图形界面掌控 Android,30-120fps 超流畅!🔥
    39
  • 5
    【01】噩梦终结flutter配安卓android鸿蒙harmonyOS 以及next调试环境配鸿蒙和ios真机调试环境-flutter项目安卓环境配置-gradle-agp-ndkVersion模拟器运行真机测试环境-本地环境搭建-如何快速搭建android本地运行环境-优雅草卓伊凡-很多人在这步就被难倒了
    122
  • 6
    Cellebrite UFED 4PC 7.71 (Windows) - Android 和 iOS 移动设备取证软件
    40
  • 7
    【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
    55
  • 8
    Android历史版本与APK文件结构
    149
  • 9
    【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
    46
  • 10
    【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
    40