AI智能
改变未来

Android开发技术之——使用ROOM数据库


第一、添加相应依赖

在应用或模块的 build.gradle 文件中添加所需工件的依赖项:

dependencies {def room_version = \"2.2.5\"implementation \"androidx.room:room-runtime:$room_version\"annotationProcessor \"androidx.room:room-compiler:$room_version\" // For Kotlin use kapt instead of annotationProcessor// optional - Kotlin Extensions and Coroutines support for Roomimplementation \"androidx.room:room-ktx:$room_version\"// 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\"}

第二、创建相应类

Entity实体,Dao,Database
在对应类中使用@Entity标注

@Entitypublic class Task{@PrimaryKey(autoGenerate = true)//主键自增private int id;}
@Daopublic class Task{@Query(\"SELECT * FROM TASK ORDER BY deadlineTime ASC\")LiveData<List<Task>> getAllTasks();@Query(\"SELECT * FROM TASK WHERE ID = :id\")LiveData<List<Task>> getTaskById(int id);@Insertvoid insertTasks(Task... task);@Updatevoid updateTasks(Task... tasks);@Deletevoid deleteTasks(Task... tasks);}
@Database(entities = {Task.class},version = 1,exportSchema = false)public abstract class TaskDataBase extends RoomDatabase {//该类对象private static TaskDataBase INSTANCE;//这是一个创建该类对象的静态方法,以后创建该类对象都使用这个方法,以确保使用的是同一个对象static synchronized  TaskDataBase getDatabase(Context context){if(INSTANCE == null){INSTANCE = Room.databaseBuilder(context.getApplicationContext(),TaskDataBase.class,\"ComponentDatabase\").build();}return  INSTANCE;}public abstract TaskDao getTaskDao();}

第三、创建仓库类,方便管理

需要注意的是,增删改的操作需要在多线程内部类中进行

public class TaskRepository {private LiveData<List<Task>> allTasksLive;private TaskDao taskDao;public TaskRepository(Context context){TaskDataBase taskDataBase = TaskDataBase.getDatabase(context.getApplicationContext());taskDao = taskDataBase.getTaskDao();allTasksLive = taskDao.getAllTasks();}//获取全部LiveData<List<Task>> getAllTasksLive(){return allTasksLive;}//增void insertTasks(Task...tasks){new  InsertAsyncTask(taskDao).execute(tasks);}//多线程内部类//增static class InsertAsyncTask extends AsyncTask<Task,Void,Void> {//需要一个数据库成员变量private TaskDao taskDao;//构造方法,获取数据库对象public InsertAsyncTask(TaskDao taskDao){this.taskDao = taskDao;}//这个是在后台线程中执行的方法,形参列表即在调用该类对象的excute方法时传递@Overrideprotected Void doInBackground(Task... tasks) {//将component插入taskDao.insertTasks(tasks);return null;}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Android开发技术之——使用ROOM数据库