一、Room 引入
1、基本介紹
- Room 在 SQLite 上提供了一個抽象層,以便在充分利用 SQLite 的強大功能的同時,能夠流暢地訪問數據庫,官方強烈建議使用 Room 而不是 SQLite
2、演示
(1)Setting
- 模塊級 build.gradle
dependencies {implementation "androidx.room:room-runtime:2.2.5"annotationProcessor "androidx.room:room-compiler:2.2.5"
}
(2)Entity
- MyStudent.java
package com.my.jetpackdemo.entity;import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;@Entity(tableName = "my_student")
public class MyStudent {@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 MyStudent(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}@Ignorepublic MyStudent(String name, int age) {this.name = name;this.age = age;}
}
- 這是一個簡單的 Java 類,并且它被標記為 Room 數據庫的實體
-
@Entity(tableName = "my_student")
:這個注解表明 MyStudent 類是一個 Room 數據庫實體,并且其對應的表名是 my_student -
@PrimaryKey(autoGenerate = true)
:這個注解表明 id 字段是這個實體的主鍵,并且它的值是自動生成的 -
@ColumnInfo
:這個注解用于描述數據庫表中的列信息,它有兩個屬性,name 表示列名,typeAffinity 表示列的數據類型 -
@Ignore
:這個注解表示 Room 在處理這個類或它的字段時應該忽略它,這通常用于構造器或方法,以避免 Room 試圖將它們映射到數據庫列
(3)Dao
- MyStudentDao.java
package com.my.jetpackdemo.dao;import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;import com.my.jetpackdemo.entity.MyStudent;import java.util.List;@Dao
public interface MyStudentDao {@Insertvoid insert(MyStudent... students);@Deletevoid delete(MyStudent... students);@Updatevoid update(MyStudent... students);@Query("SELECT * FROM my_student")List<MyStudent> getAll();@Query("SELECT * FROM my_student WHERE id = :id")MyStudent getById(int id);
}
- 這是一個接口,它用于與 Room 數據庫進行交互,以操作 MyStudent 實體,這個接口使用了 Room 提供的注解來定義數據訪問對象(DAO)的方法
-
insert(MyStudent... students)
,@Dao
:這個注解表明這個接口是一個 Room 數據庫的數據訪問對象 -
delete(MyStudent... students)
,@Insert
:這個注解表明這個方法用于向數據庫中插入數據,方法接受一個或多個 MyStudent 對象作為參數,并將它們插入到數據庫中 -
update(MyStudent... students)
,@Delete
:這個注解表明這個方法用于從數據庫中刪除數據,方法接受一個或多個 MyStudent 對象作為參數,并從數據庫中刪除它們 -
getAll()
,@Update
:這個注解表明這個方法用于更新數據庫中的數據,方法接受一個或多個 MyStudent 對象作為參數,并更新數據庫中對應的記錄 -
getAll()
,@Query
:這個注解用于定義自定義的 SQL 查詢,這個方法返回一個 MyStudent 對象的列表,它包含了數據庫中所有的學生記錄 -
getById(int id)
,@Query
:這個注解用于定義自定義的 SQL 查詢,這個方法根據給定的 id 返回對應的 MyStudent 對象,如果沒有找到對應的記錄,它可能會返回 null
(4)Database
- MyDatabase.java
package com.my.jetpackdemo.database;import android.content.Context;import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;import com.my.jetpackdemo.dao.MyStudentDao;
import com.my.jetpackdemo.entity.MyStudent;@Database(entities = {MyStudent.class}, version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {private static final String DATABASE_NAME = "my_db.db";private static MyDatabase myDatabase;public static synchronized MyDatabase getInstance(Context context) {if (myDatabase == null) {myDatabase = Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, DATABASE_NAME).build();}return myDatabase;}public abstract MyStudentDao getMyStudentDao();
}
- 這是一個抽象類,它擴展了 Room 的 RoomDatabase 類,這個類代表了你的 Room 數據庫,并且它包含了與數據庫交互的 DAO(數據訪問對象)的抽象方法,
@Database
注解標記了這個類為一個 Room 數據庫
-
entities = {MyStudent.class}
:表示這個數據庫包含 MyStudent 實體 -
version = 1
:表示數據庫的版本號,當實體或數據庫結構發生變化時,需要增加這個版本號 -
exportSchema = false
:表示不導出數據庫的 schema
(5)Activity Layout
- activity_room_demo.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=".RoomDemoActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:paddingTop="20dp"android:paddingBottom="20dp"><Buttonandroid:id="@+id/button1"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="10dp"android:layout_weight="1"android:onClick="add"android:text="新增" /><Buttonandroid:id="@+id/button2"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="20dp"android:layout_weight="1"android:onClick="delete"android:text="刪除" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:paddingTop="20dp"android:paddingBottom="20dp"><Buttonandroid:id="@+id/butto3"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="10dp"android:layout_weight="1"android:onClick="update"android:text="修改" /><Buttonandroid:id="@+id/button4"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="20dp"android:layout_weight="1"android:onClick="get"android:text="查詢" /></LinearLayout><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/rv_my_student"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- room_demo_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="50dp"android:orientation="vertical"><TextViewandroid:id="@+id/tv_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:text="TextView" /><TextViewandroid:id="@+id/tv_name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="TextView" /><TextViewandroid:id="@+id/tv_age"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:text="TextView" />
</RelativeLayout>
(6)Adapter
- MyStudentRecyclerViewAdapter.java
package com.my.jetpackdemo.adapter;import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;import com.my.jetpackdemo.R;
import com.my.jetpackdemo.entity.MyStudent;import java.util.ArrayList;
import java.util.List;public class MyStudentRecyclerViewAdapter extends RecyclerView.Adapter<MyStudentRecyclerViewAdapter.MyStudentRecyclerViewHolder> {private Context context;private List<MyStudent> myStudentList;public MyStudentRecyclerViewAdapter(Context context) {this.context = context;myStudentList = new ArrayList<>();}public MyStudentRecyclerViewAdapter(Context context, List<MyStudent> myStudentList) {this.context = context;this.myStudentList = myStudentList;}public List<MyStudent> getMyStudentList() {return myStudentList;}public void setMyStudentList(List<MyStudent> myStudentList) {this.myStudentList = myStudentList;}@NonNull@Overridepublic MyStudentRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {View view = View.inflate(context, R.layout.room_demo_item, null);MyStudentRecyclerViewHolder myStudentRecyclerViewHolder = new MyStudentRecyclerViewHolder(view);return myStudentRecyclerViewHolder;}@Overridepublic void onBindViewHolder(@NonNull MyStudentRecyclerViewHolder holder, int position) {MyStudent myStudent = myStudentList.get(position);holder.tvId.setText(String.valueOf(myStudent.id));holder.tvName.setText(myStudent.name);holder.tvAge.setText(String.valueOf(myStudent.age));}@Overridepublic int getItemCount() {return myStudentList.size();}static class MyStudentRecyclerViewHolder extends RecyclerView.ViewHolder {TextView tvId;TextView tvName;TextView tvAge;public MyStudentRecyclerViewHolder(@NonNull View itemView) {super(itemView);tvId = itemView.findViewById(R.id.tv_id);tvName = itemView.findViewById(R.id.tv_name);tvAge = itemView.findViewById(R.id.tv_age);}}
}
(7)Activity Code
- RoomDemoActivity.java
package com.my.jetpackdemo;import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;import com.my.jetpackdemo.adapter.MyStudentRecyclerViewAdapter;
import com.my.jetpackdemo.dao.MyStudentDao;
import com.my.jetpackdemo.database.MyDatabase;
import com.my.jetpackdemo.entity.MyStudent;import java.util.List;public class RoomDemoActivity extends AppCompatActivity {private RecyclerView rvMyStudent;private MyStudentRecyclerViewAdapter myStudentRecyclerViewAdapter;private MyDatabase myDatabase;private MyStudentDao myStudentDao;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_room_demo);rvMyStudent = findViewById(R.id.rv_my_student);myStudentRecyclerViewAdapter = new MyStudentRecyclerViewAdapter(this);rvMyStudent.setAdapter(myStudentRecyclerViewAdapter);rvMyStudent.setLayoutManager(new LinearLayoutManager(this));myDatabase = MyDatabase.getInstance(this);myStudentDao = myDatabase.getMyStudentDao();}public void add(View view) {MyStudent myStudent1 = new MyStudent("jack", 20);MyStudent myStudent2 = new MyStudent("tom", 21);new AddMyStudentTask().execute(myStudent1, myStudent2);}public void delete(View view) {new DeleteMyStudentTask().execute(new MyStudent(1, "", 0));}public void update(View view) {new UpdateMyStudentTask().execute(new MyStudent(2, "my", 100));}public void get(View view) {new GetMyStudentTask().execute();}class AddMyStudentTask extends AsyncTask<MyStudent, Void, Void> {@Overrideprotected Void doInBackground(MyStudent... students) {myStudentDao.insert(students);return null;}}class DeleteMyStudentTask extends AsyncTask<MyStudent, Void, Void> {@Overrideprotected Void doInBackground(MyStudent... students) {myStudentDao.delete(students);return null;}}class UpdateMyStudentTask extends AsyncTask<MyStudent, Void, Void> {@Overrideprotected Void doInBackground(MyStudent... students) {myStudentDao.update(students);return null;}}class GetMyStudentTask extends AsyncTask<Void, Void, Void> {@Overrideprotected Void doInBackground(Void... voids) {List<MyStudent> all = myStudentDao.getAll();myStudentRecyclerViewAdapter.setMyStudentList(all);return null;}@Overrideprotected void onPostExecute(Void unused) {super.onPostExecute(unused);myStudentRecyclerViewAdapter.notifyDataSetChanged();}}
}
3、Room 注解
- Entity 使用的注解
注解 | 說明 |
---|---|
@Entity | 用于標記一個類作為數據庫中的表 可以使用 tableName 屬性來指定表名 如果類中的字段需要映射到數據庫中的列,則字段必須有訪問修飾符(public、protected 或默認) |
@PrimaryKey | 用于標記一個字段作為表的主鍵 可以設置 autoGenerate 為 true 來自動生成主鍵值 |
@ColumnInfo | 用于標記一個字段并提供額外的列信息 可以使用 name 屬性來指定列名 可以使用 index 屬性來創建索引 |
@Ignore | 用于標記一個字段或方法,使其不被 Room 考慮為數據庫的一部分 |
- Dao 使用的注解
注解 | 說明 |
---|---|
@Dao | 用于標記一個接口作為數據訪問對象(DAO) DAO 接口中定義的方法用于執行數據庫的增刪改查操作 Room 會在編譯時生成這個接口的實現 |
@Insert、@Update、@Delete、@Query | 用于在 DAO 接口中標記方法,分別用于插入、更新、刪除和查詢數據@Query 注解允許編寫自定義的 SQL 查詢語句 |
- Database 使用的注解
注解 | 說明 |
---|---|
@Database | 用于標記一個抽象類作為數據庫的入口點 可以使用 entities 屬性來指定包含在該數據庫中的所有實體類 使用 version 屬性來指定數據庫的版本號,以便進行遷移 |
二、Room 優化
1、基本介紹
- 目前每當數據庫數據發生變化時,都需要開啟一個工作線程去重新獲取數據庫中的數據,可以當數據發生變化時,通過 LiveData 通知 View 層,實現數據自動更新
2、演示
(1)Entity
- MyStudent.java
package com.my.room2.entity;import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;@Entity(tableName = "my_student")
public class MyStudent {@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 MyStudent(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}@Ignorepublic MyStudent(String name, int age) {this.name = name;this.age = age;}
}
(2)Dao
- MyStudentDao.java
package com.my.room2.dao;import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;import com.my.room2.entity.MyStudent;import java.util.List;@Dao
public interface MyStudentDao {@Insertvoid insert(MyStudent... students);@Deletevoid delete(MyStudent... students);@Query("DELETE FROM my_student")void deleteAll();@Updatevoid update(MyStudent... students);@Query("SELECT * FROM my_student")LiveData<List<MyStudent>> getAllLive();
}
(3)Database
- MyDatabase.java
package com.my.room2.database;import android.content.Context;import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;import com.my.room2.dao.MyStudentDao;
import com.my.room2.entity.MyStudent;@Database(entities = {MyStudent.class}, version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {private static final String DATABASE_NAME = "my_db.db";private static MyDatabase myDatabase;public static synchronized MyDatabase getInstance(Context context) {if (myDatabase == null) {myDatabase = Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, DATABASE_NAME).build();}return myDatabase;}public abstract MyStudentDao getMyStudentDao();
}
(4)Repository
- MyStudentRepository.java
package com.my.room2.repository;import android.content.Context;
import android.os.AsyncTask;
import android.view.View;import androidx.lifecycle.LiveData;import com.my.room2.RoomDemoActivity;
import com.my.room2.dao.MyStudentDao;
import com.my.room2.database.MyDatabase;
import com.my.room2.entity.MyStudent;import java.util.List;public class MyStudentRepository {private MyStudentDao myStudentDao;public MyStudentRepository(Context context) {myStudentDao = MyDatabase.getInstance(context).getMyStudentDao();}// ----------------------------------------------------------------------------------------------------public void add(MyStudent... myStudents) {new AddMyStudentTask().execute(myStudents);}public void delete(MyStudent myStudent) {new DeleteMyStudentTask().execute(myStudent);}public void deleteAll() {new DeleteAllMyMyStudentTask().execute();}public void update(MyStudent myStudent) {new UpdateMyStudentTask().execute(myStudent);}public LiveData<List<MyStudent>> getAll() {return myStudentDao.getAllLive();}// ----------------------------------------------------------------------------------------------------class AddMyStudentTask extends AsyncTask<MyStudent, Void, Void> {@Overrideprotected Void doInBackground(MyStudent... students) {myStudentDao.insert(students);return null;}}class DeleteMyStudentTask extends AsyncTask<MyStudent, Void, Void> {@Overrideprotected Void doInBackground(MyStudent... students) {myStudentDao.delete(students);return null;}}class DeleteAllMyMyStudentTask extends AsyncTask<Void, Void, Void> {@Overrideprotected Void doInBackground(Void... voids) {myStudentDao.deleteAll();return null;}}class UpdateMyStudentTask extends AsyncTask<MyStudent, Void, Void> {@Overrideprotected Void doInBackground(MyStudent... students) {myStudentDao.update(students);return null;}}
}
(5)ViewModel
- MyStudentViewModel.java
package com.my.room2.viewmodel;import android.app.Application;import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;import com.my.room2.entity.MyStudent;
import com.my.room2.repository.MyStudentRepository;import java.util.List;public class MyStudentViewModel extends AndroidViewModel {private MyStudentRepository myStudentRepository;public MyStudentViewModel(@NonNull Application application) {super(application);myStudentRepository = new MyStudentRepository(application);}public void add(MyStudent... myStudents) {myStudentRepository.add(myStudents);}public void delete(MyStudent myStudent) {myStudentRepository.delete(myStudent);}public void deleteAll() {myStudentRepository.deleteAll();}public void update(MyStudent myStudent) {myStudentRepository.update(myStudent);}public LiveData<List<MyStudent>> getAll() {return myStudentRepository.getAll();}
}
(6)Activity Layout
- activity_room_demo.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=".RoomDemoActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:paddingTop="20dp"android:paddingBottom="20dp"><Buttonandroid:id="@+id/button1"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="20dp"android:layout_marginRight="10dp"android:layout_weight="1"android:onClick="add"android:text="新增" /><Buttonandroid:id="@+id/button2"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:layout_weight="1"android:onClick="delete"android:text="刪除" /><Buttonandroid:id="@+id/butto3"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="20dp"android:layout_weight="1"android:onClick="update"android:text="修改" /></LinearLayout><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/rv_my_student"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- room_demo_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="50dp"android:orientation="vertical"><TextViewandroid:id="@+id/tv_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_centerVertical="true"android:text="TextView" /><TextViewandroid:id="@+id/tv_name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="TextView" /><TextViewandroid:id="@+id/tv_age"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:text="TextView" />
</RelativeLayout>
(7)Adapter
- MyStudentRecyclerViewAdapter.java
package com.my.room2.adapter;import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;import com.my.room2.R;
import com.my.room2.entity.MyStudent;import java.util.ArrayList;
import java.util.List;public class MyStudentRecyclerViewAdapter extends RecyclerView.Adapter<MyStudentRecyclerViewAdapter.MyStudentRecyclerViewHolder> {private Context context;private List<MyStudent> myStudentList;public MyStudentRecyclerViewAdapter(Context context) {this.context = context;myStudentList = new ArrayList<>();}public MyStudentRecyclerViewAdapter(Context context, List<MyStudent> myStudentList) {this.context = context;this.myStudentList = myStudentList;}public List<MyStudent> getMyStudentList() {return myStudentList;}public void setMyStudentList(List<MyStudent> myStudentList) {this.myStudentList = myStudentList;}@NonNull@Overridepublic MyStudentRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {View view = View.inflate(context, R.layout.room_demo_item, null);MyStudentRecyclerViewHolder myStudentRecyclerViewHolder = new MyStudentRecyclerViewHolder(view);return myStudentRecyclerViewHolder;}@Overridepublic void onBindViewHolder(@NonNull MyStudentRecyclerViewHolder holder, int position) {MyStudent myStudent = myStudentList.get(position);holder.tvId.setText(String.valueOf(myStudent.id));holder.tvName.setText(myStudent.name);holder.tvAge.setText(String.valueOf(myStudent.age));}@Overridepublic int getItemCount() {return myStudentList.size();}static class MyStudentRecyclerViewHolder extends RecyclerView.ViewHolder {TextView tvId;TextView tvName;TextView tvAge;public MyStudentRecyclerViewHolder(@NonNull View itemView) {super(itemView);tvId = itemView.findViewById(R.id.tv_id);tvName = itemView.findViewById(R.id.tv_name);tvAge = itemView.findViewById(R.id.tv_age);}}
}
(8)Activity Code
- RoomDemoActivity.java
package com.my.room2;import android.os.Bundle;
import android.view.View;import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;import com.my.room2.adapter.MyStudentRecyclerViewAdapter;
import com.my.room2.dao.MyStudentDao;
import com.my.room2.database.MyDatabase;
import com.my.room2.entity.MyStudent;
import com.my.room2.viewmodel.MyStudentViewModel;import java.util.List;public class RoomDemoActivity extends AppCompatActivity {private RecyclerView rvMyStudent;private MyStudentRecyclerViewAdapter myStudentRecyclerViewAdapter;private MyStudentViewModel myStudentViewModel;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_room_demo);rvMyStudent = findViewById(R.id.rv_my_student);myStudentRecyclerViewAdapter = new MyStudentRecyclerViewAdapter(this);rvMyStudent.setAdapter(myStudentRecyclerViewAdapter);rvMyStudent.setLayoutManager(new LinearLayoutManager(this));myStudentViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MyStudentViewModel.class);myStudentViewModel.getAll().observe(this, new Observer<List<MyStudent>>() {@Overridepublic void onChanged(List<MyStudent> myStudents) {myStudentRecyclerViewAdapter.setMyStudentList(myStudents);myStudentRecyclerViewAdapter.notifyDataSetChanged();}});}public void add(View view) {MyStudent myStudent1 = new MyStudent("jack", 20);MyStudent myStudent2 = new MyStudent("tom", 21);myStudentViewModel.add(myStudent1, myStudent2);}public void delete(View view) {MyStudent myStudent = new MyStudent(1, "", 0);myStudentViewModel.delete(myStudent);}public void update(View view) {MyStudent myStudent = new MyStudent(2, "my", 100);myStudentViewModel.update(myStudent);}public void getAll(View view) {}
}