Jetpack-Room

embedded/2024/10/15 4:52:27/

Room是Android Jetpack中的一个组件,它提供了一个抽象层,帮助开发者在本地数据库(如SQLite)上进行持久化数据存储。Room通过简化数据库操作,使得数据管理变得更加容易和高效。

Room重要的概念

  • 实体(Entity):实体是用于表示数据库表的类。通过使用@Entity注解,可以定义一个实体类,并将其映射到数据库表。实体类中的属性对应于数据库表中的列。
  • 数据库(Database):数据库类是一个抽象类,用于定义数据库版本和包含的实体。通过使用@Database注解,可以创建一个继承自RoomDatabase的抽象类,并指定实体类和数据库版本。
  • 数据访问对象(DAO):DAO接口用于定义对数据库的访问操作。通过使用@Dao注解,可以定义一个接口,并在其中声明各种CRUD方法。这些方法会被转换为对应的SQL语句。
    在这里插入图片描述

在Android开发中,使用DAO(Data Access Object)、Repository和ViewModel的架构模式是为了实现数据与界面的清晰分离,提高应用的可维护性和扩展性。

  • DAO(Data Access Object):DAO是负责直接与数据库交互的组件。它定义了操作数据库的方法,如查询、插入、更新和删除。通过使用DAO,开发者可以将数据库操作逻辑从业务逻辑中分离出来,使得代码更加模块化和易于管理。
  • Repository:Repository层作为数据源和ViewModel之间的中介,负责处理数据请求和响应。它可以封装多个数据源,例如本地数据库和远程API,并提供一个统一的接口供ViewModel调用。这样,当数据源发生变化时,只需要修改Repository层,而不必触及ViewModel或View层,从而提高了代码的复用性和可维护性。
  • ViewModel:ViewModel是一个用于存储和管理UI相关数据的架构组件。它的主要目的是将UI控制器(如Activity和Fragment)与数据相关的业务逻辑分开,使得UI控制器能够专注于展示数据和响应用户交互,而数据的获取和处理则交由ViewModel来管理。这种分离能够使代码更加清晰、易于测试和维护。

案例:Room + ViewModel + LiveData 实现操作

使用步骤:
1.引入依赖

java">    def room_version = "2.6.1"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version"

2.定义实体

java">@Entity(tableName = "student")
public class Student {@PrimaryKey(autoGenerate = true)@ColumnInfo(name = "id",typeAffinity = ColumnInfo.INTEGER)public int id;@ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)public String name;@ColumnInfo(name = "age",typeAffinity = ColumnInfo.INTEGER)public int age;public Student(int id, int age, String name) {this.id = id;this.age = age;this.name = name;}@Ignorepublic Student(int age, String name) {this.age = age;this.name = name;}@Ignorepublic Student(int id) {this.id = id;}
}

3.定义Dao

java">@Dao
public interface StudentDao {@Insertvoid insert(Student... students);@Deletevoid delete(Student... students);@Updatevoid update(Student... students);@Query("select * from student")List<Student> getAllStudent();@Query("select * from student where id = :id")Student getStudentById(int id);
}

3.定义MyDatabase

java">@Database(entities = {Student.class}, version = 1,exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {private static final String DB_NAME = "my_db.db";private static  MyDatabase mInstance;public static synchronized MyDatabase getInstance(Context context){if(mInstance == null){mInstance = Room.databaseBuilder(context.getApplicationContext(),MyDatabase.class,DB_NAME).build();}return mInstance;}public abstract StudentDao studentDao();
}

4.定义StudentRepository

java">public class StudentRepository {private StudentDao studentDao;public StudentRepository(Context context){MyDatabase db = MyDatabase.getInstance(context);studentDao = db.studentDao();}public void insert(Student... students){new InsertStudentTask(studentDao).execute(students);}class InsertStudentTask extends AsyncTask<Student, Void,Void>{private StudentDao studentDao;public InsertStudentTask(StudentDao studentDao) {this.studentDao = studentDao;}@Overrideprotected Void doInBackground(Student... students) {studentDao.insert(students);return null;}}public void update(Student... students){new UpdateStudentTask(studentDao).execute(students);}class UpdateStudentTask extends AsyncTask<Student, Void,Void>{private StudentDao studentDao;public UpdateStudentTask(StudentDao studentDao) {this.studentDao = studentDao;}@Overrideprotected Void doInBackground(Student... students) {studentDao.update(students);return null;}}public void delete(Student... students){new DeleteStudentTask(studentDao).execute(students);}class DeleteStudentTask extends AsyncTask<Student, Void,Void>{private StudentDao studentDao;public DeleteStudentTask(StudentDao studentDao) {this.studentDao = studentDao;}@Overrideprotected Void doInBackground(Student... students) {studentDao.delete(students);return null;}}public void deleteAllStudent(){new DeleteAllStudentTask(studentDao).execute();}class DeleteAllStudentTask extends AsyncTask<Void, Void,Void>{private StudentDao studentDao;public DeleteAllStudentTask(StudentDao studentDao) {this.studentDao = studentDao;}@Overrideprotected Void doInBackground(Void... voids) {studentDao.deleteAll();return null;}}public LiveData<List<Student>> getAllStudent(){return studentDao.getAllStudent();}}

5.定义StudentViewModel

java">public class StudentViewModel extends AndroidViewModel {private StudentRepository studentRepository;public StudentViewModel(@NonNull Application application) {super(application);studentRepository = new StudentRepository(application);}public void insert(Student... students){studentRepository.insert(students);}public void delete(Student... students){studentRepository.delete(students);}public void deleteAllStudent(){studentRepository.deleteAllStudent();}public void update(Student... students){studentRepository.update(students);}public LiveData<List<Student>> getAllStudnet(){return studentRepository.getAllStudent();}}

6.在MainActivity操作实现数据新增删除等操作

java">public class MainActivity extends AppCompatActivity {private StudentRecyclerViewAdapter adapter;private StudentViewModel studentViewModel;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RecyclerView recyclerView = findViewById(R.id.recyclerView);recyclerView.setLayoutManager(new LinearLayoutManager(this));List<Student> studentList = new ArrayList<>();adapter = new StudentRecyclerViewAdapter(studentList);recyclerView.setAdapter(adapter);studentViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory()).get(StudentViewModel.class);studentViewModel.getAllStudnet().observe(this, new Observer<List<Student>>() {@Overridepublic void onChanged(List<Student> students) {adapter.setStudentList(students);adapter.notifyDataSetChanged();}});}public void mInsert(View view) {Student s1 = new Student(18,"张三");Student s2 = new Student(19,"李四");studentViewModel.insert(s2);studentViewModel.insert(s1);}public void mUpdate(View view) {Student s1 = new Student(4,99,"新张三");studentViewModel.update(s1);}public void mDelete(View view) {Student s1 = new Student(2);studentViewModel.delete(s1);}public void mClear(View view) {studentViewModel.deleteAllStudent();}
}

http://www.ppmy.cn/embedded/127695.html

相关文章

【ARM 嵌入式 编译系列 10.8 -- 介绍 GCC Toolchain】

> ARM GCC 编译精讲系列课程链接 < 文章目录 GCC 工具链详细介绍工具链简介详细介绍1. GCC&#xff08;GNU Compiler Collection&#xff09;2. Newlib&#xff08;C 标准库&#xff09;3. Binutils&#xff08;GNU 二进制工具&#xff09;4. GDB&#xff08;GNU 调试器&…

服务器-公网和内网之分

公网服务器和内网服务器是有区分的。‌ 公网服务器是指可以直接通过互联网访问的服务器&#xff0c;通常部署在数据中心或云平台上&#xff0c;拥有一个公网IP地址。它可以被任何具有互联网连接的设备访问&#xff0c;常用于托管网站、提供云服务或远程访问等应用场景‌。内网服…

transformer的基础知识

transformer的基础知识 transformer网络结构图 seq2seq 一般Seq2seq会分成两部分:Encoder、Decoder。 Encoder Transformer 中的 Encoder 就是用的 Self-attention。 encoder的内部结构 补充:block的内部结构主要由self-attention和全连接神经网络所构成。 在原来的论…

个人博客搭建 | Hexo框架

文章目录 1.Hexo安装2.创建博客3.将博客通过GitHub来部署4.更换主题 1.Hexo安装 Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown&#xff08;或其他标记语言&#xff09;解析文章&#xff0c;在几秒内&#xff0c;即可利用靓丽的主题生成静态网页。搭建Hexo首先要…

成都睿明智科技有限公司抖音电商服务佼佼者

在当今这个数字化浪潮汹涌的时代&#xff0c;抖音电商以其独特的魅力迅速崛起&#xff0c;成为众多商家竞相追逐的新蓝海。而在这场电商盛宴中&#xff0c;专业的服务商如同灯塔一般&#xff0c;为迷茫的商家指引方向。今天&#xff0c;我们就来深入探讨一家备受瞩目的服务商—…

temp表空间的文件被误删,expdp导出查询都报错了?

处理方式&#xff1a;新加临时文件&#xff0c;删除旧临时文件&#xff08;用文件号&#xff09;即可解决。 oracletest:/home/oracle>expdp \/ as sysdba\ directoryEXPDIR dumpfiletest_meta1.dmp contentmetadata_only logfile5y-meta1.log fully Export: Release 11.…

数据结构编程实践20讲(Python版)—12树状数组

本文目录 12 树状数组(Binary Indexed Tree / Fenwick Tree)S1 说明S2 示例S3 问题1:二维树状数组的单点更新和区域求和S4 问题2:求解逆序数对S5 问题3:动态求解第 K 小(大)数S6 问题4:频率计数和排名查询S7 问题5:求解最长递增子序列问题往期链接 01 数组02 链表03 栈0…

进程相关及守护进程

一、进程 1.1 wait / waitpid 函数的使用 #include <sys/types.h> #include <sys/wait.h>pid_t wait(int *wstatus); 功能&#xff1a;阻塞等待子进程结束&#xff0c;为子进程回收资源 参数&#xff1a;wstatus&#xff1a;子进程退出的状态--如果不关注&#x…