Android-room的学习
目录
关于ROOM
1.Room有3个主要的组件
2.Room 不同组件之间的关系如图所示
3.导入ROOM(使用 Room 需要添加依赖)
4.(实现数据库操作的步骤)以下代码段包含具有一个实体和一个 DAO 的示例数据库配置
实例demo
1.Student.java
2.StudentDao.java
3.StudentDatabase.java
4.MainActivity.java
5.activity_main.xml
参考资料
关于ROOM
Room 在 SQLite 上提供了一个抽象层,以便在充分利用 SQLite 的强大功能的同时,能够流畅地访问数据库。
处理大量结构化数据的应用可极大地受益于在本地保留这些数据。最常见的用例是缓存相关数据。这样,当设备无法访问网络时,用户仍可在离线状态下浏览相应内容。设备之后重新连接到网络后,用户发起的所有内容更改都会同步到服务器。
1.Room有3个主要的组件
数据库:包含数据库持有者,并作为应用已保留的持久关系型数据的底层连接的主要接入点。
使用
@Database
注释的类应满足以下条件:
- 是扩展
RoomDatabase
的抽象类。- 在注释中添加与数据库关联的实体列表。
- 包含具有 0 个参数且返回使用
@Dao
注释的类的抽象方法。在运行时,您可以通过调用
Room.databaseBuilder()
或Room.inMemoryDatabaseBuilder()
获取Database
的实例。Entity:表示数据库中的表。
DAO:包含用于访问数据库的方法。
应用使用 Room 数据库来获取与该数据库关联的数据访问对象 (DAO)。然后,应用使用每个 DAO 从数据库中获取实体,然后再将对这些实体的所有更改保存回数据库中。最后,应用使用实体来获取和设置与数据库中的表列相对应的值。
2.Room 不同组件之间的关系如图所示
3.导入ROOM(使用 Room 需要添加依赖)
dependencies {def room_version = "2.2.0-alpha01"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version" // use kapt for Kotlin// optional - RxJava support for Roomimplementation "androidx.room:room-rxjava2:$room_version"// optional - Guava support for Room, including Optional and ListenableFutureimplementation "androidx.room:room-guava:$room_version"// Test helperstestImplementation "androidx.room:room-testing:$room_version"
}
4.(实现数据库操作的步骤)以下代码段包含具有一个实体和一个 DAO 的示例数据库配置
1.User.java (必须先创建一个需要映射的实体类,用@Entity进行注解)
@Entity
public class User {@PrimaryKeyprivate int uid;@ColumnInfo(name = "first_name")private String firstName;@ColumnInfo(name = "last_name")private String lastName;// Getters and setters are ignored for brevity,// but they're required for Room to work.
}
2.UserDao.java( 创建一个操作实体类的dao接口,用@Dao进行注解)
@Dao
public interface UserDao {@Query("SELECT * FROM user")List<User> getAll();@Query("SELECT * FROM user WHERE uid IN (:userIds)")List<User> loadAllByIds(int[] userIds);@Query("SELECT * FROM user WHERE first_name LIKE :first AND "+ "last_name LIKE :last LIMIT 1")User findByName(String first, String last);@Insertvoid insertAll(User... users);@Deletevoid delete(User user);
}
3.AppDatabase.java( 创建一个抽象类,添加@Database注解)
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {public abstract UserDao userDao();
}
4.在创建上面的文件之后,使用以下代码获得创建数据库的实例:
AppDatabase db = Room.databaseBuilder(getApplicationContext(),AppDatabase.class, "database-name").build();
实例demo
1.Student.java
package com.example.applicationroom;import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;@Entity
public class Student {@PrimaryKey(autoGenerate = true) // 设置主键,并且自动生长private int id;@ColumnInfo(name = "username") // 设置别名,如果不设置就默认为变量名private String name;public Student(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
2.StudentDao.java
package com.example.applicationroom;import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;import java.util.List;@Dao
public interface StudentDao {// 在这里声明数据库的操作,如增删改查@Insertpublic void insertStudents(Student...students);// 可以传递三个参数@Updatevoid updateStudents(Student...students);@Deletevoid deleteStudents(Student...students);@Query("DELETE FROM STUDENT")void deleteAllStudents();@Query("SELECT * FROM STUDENT ORDER BY id ASC") // 升序排列List<Student> getAllStudents();}
3.StudentDatabase.java
package com.example.applicationroom;import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {Student.class}, version = 6, exportSchema = false)
public abstract class StudentDatabase extends RoomDatabase {public abstract StudentDao getStudentDao(); // 若有多个 Entity,则应该写多个 Dao/* private static StudentDatabase mInstance;public StudentDatabase() { }public static StudentDatabase getsInstance(Context context) {if (mInstance == null) {synchronized (StudentDatabase.class) {if (mInstance == null) {mInstance = Room.databaseBuilder(context.getApplicationContext(),StudentDatabase.class, "StudentDb").fallbackToDestructiveMigration().addMigrations().allowMainThreadQueries().build();}}}return mInstance;}*/}
4.MainActivity.java
package com.example.applicationroom;import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;import java.util.List;public class MainActivity extends AppCompatActivity {StudentDatabase studentDatabase;StudentDao studentDao;TextView textView;Button buttonInsert,buttonUpdate,buttonDelete,buttonClear;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = findViewById(R.id.textView);// allowMainThreadQueries() 强制允许在主线程执行,真实开发中不要这么做//studentDatabase = StudentDatabase.getsInstance(this);//studentDao = studentDatabase.studentDao();// allowMainThreadQueries() 强制允许在主线程执行,真实开发中不要这么做studentDatabase = Room.databaseBuilder(this,StudentDatabase.class,"word_database").allowMainThreadQueries().build();studentDao = studentDatabase.getStudentDao();updateView();buttonInsert = findViewById(R.id.buttonInsert);buttonUpdate = findViewById(R.id.buttonUpdate);buttonDelete = findViewById(R.id.buttonDelete);buttonClear = findViewById(R.id.buttonClear);buttonInsert.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Student student1 = new Student(1,"吴美丽");Student student2 = new Student(2,"张漂亮");studentDao.insertStudents(student1,student2);updateView();}});buttonClear.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {studentDao.deleteAllStudents();updateView();}});buttonUpdate.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Student student3= new Student(3,"马可爱");studentDao.updateStudents(student3);updateView();}});buttonDelete.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Student student = new Student(0,"");studentDao.deleteStudents(student);updateView();}});}void updateView(){List<Student> list = studentDao.getAllStudents();String text = "";for(int i = 0; i < list.size(); i++){Student student= list.get(i);text += student.getId() + ":" + student.getName() + "\n";}textView.setText(text);}
}
5.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"><androidx.constraintlayout.widget.Guidelineandroid:id="@+id/guideline"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"app:layout_constraintGuide_begin="188dp" /><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"tools:layout_editor_absoluteX="-16dp"tools:layout_editor_absoluteY="51dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><Buttonandroid:id="@+id/buttonUpdate"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="UPDATE" /><Buttonandroid:id="@+id/buttonInsert"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="INSERT" /><Buttonandroid:id="@+id/buttonDelete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="DELETE" /><Buttonandroid:id="@+id/buttonClear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="CLEAR" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="TextView" /></LinearLayout></ScrollView></androidx.constraintlayout.widget.ConstraintLayout>
图一:插入数据
图二:清空数据
保存的数据库文件,可以在存储中找到,如图:
参考资料:
使用 Room 将数据保存到本地数据库
【Android-Room数据库系列】—— Room 基础
Android-room的学习相关推荐
- 基于 Android NDK 的学习之旅-----资源释放
基于 Android NDK 的学习之旅-----资源释放 做上一个项目的时候因为与C引擎交互频繁,有时候会突然莫名其妙的的整个应用程序直接挂掉.因为我是学Java 开始的,所以对主动释放内存没多大概 ...
- 基于 Android NDK 的学习之旅----- C调用Java
2019独角兽企业重金招聘Python工程师标准>>> 基于 Android NDK 的学习之旅----- C调用Java 许多成熟的C引擎要移植到Android 平台上使用 , 一 ...
- 基于 Android NDK 的学习之旅-----数据传输二(引用数据类型)(附源码)
基于 Android NDK 的学习之旅-----数据传输(引用数据类型) 接着上篇文章继续讲.主要关于引用类型的数据传输,本文将介绍字符串传输和自定义对象的传输. 1.主要流程 1. String ...
- 【转】基于 Android NDK 的学习之旅-----数据传输(引用数据类型)
原文网址:http://www.cnblogs.com/luxiaofeng54/archive/2011/08/20/2147086.html 基于 Android NDK 的学习之旅-----数据 ...
- 基于android的交流平台,基于Android的移动学习交流平台的设计与实现
摘要: 随着移动互联网技术的不断发展,智能手机的不断普及,现在越来越多的人通过手机等智能设备来进行学习和交流.为了满足教师和学生实时的沟通交流,提高学生的学习兴趣和效率,本文设计了基于Android的 ...
- Android基础知识学习
一.Android编译过程 初始化参数设置 检查环境变量与目标环境 选择lunch并读取目标配置和平台信息 清空输出目录 编译 生成升级包 二. ./build/envsetup.sh分析 加载编译命 ...
- 基于 Android NDK 的学习之旅-----Java 调用C(附源码)
基于 Android NDK 的学习之旅-----Java 调用C 随便谈谈为什么要Java调用C 吧: 我认为: 1. 有些公司开发Android项目的时候, 许多组件功能可能是C中已经实现了,所 ...
- Android 渗透测试学习手册 翻译完成!
Android 渗透测试学习手册 中文版 原书:Learning Pentesting for Android Devices 译者:飞龙 在线阅读 PDF格式 EPUB格式 MOBI格式 代码仓库 ...
- android自定义View学习(一)----创建一个视图类
创建一个视图类 精心设计的自定义视图与其他精心设计的类非常相似.它使用易于使用的界面封装了一组特定的功能,它可以高效地使用CPU和内存,等等.不过,作为一个设计良好的班级,自定义视图应该: 符合And ...
- 2013-2-19 Android之ActionBar学习(转)
2013-2-19 Android之ActionBar学习(转) Android之ActionBar学习 - Android移动开发技术文章_手机开发 - 红黑联盟 资讯 | 安全 | 论坛 | ...
最新文章
- linux启动sql server数据库,SQL Server数据库启动过程详解及启动不起来的问题分析及解决方法...
- 聊聊springboot elasticsearch healthIndicator
- linux创建隐藏进程6,在Linux 2.6内核下实现进程隐藏
- 存储过程系列之调试存储过程 SQL Server 2005
- Android APK反编译就这么简单 详解(图文详解)
- C++在哪几种情况只能用intialization list 而不能用assignment?
- .net框架读书笔记---基础类型
- springsession分布式登录被覆盖_拉勾 分布式 学习小结
- K8s 集群搭建过程中遇到的问题的解决方法
- CodeForces - 1013B And 与运算暴力
- Java Web servletConfig 对象
- 安装完 SQL Server 2008 后没有 SQL Server Management Studio
- web前端30个项目列表,学完即可上手做项目
- WebStorm 支持 rpx
- 瀑布流 ajax 预载入 json
- 网易云类音乐--主页与登录界面结构html+css实现(三)
- 物联网价值链中只有软件或者平台/服务才会赚大钱?
- csp-202203
- linux 文件中查找内容
- oracle四大语言_oracle是用什么语言?是SQL语言吗?