当前位置: 首页 > news >正文

Jetpack - Room(Room 引入、Room 优化)

一、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 数据库的实体
  1. @Entity(tableName = "my_student"):这个注解表明 MyStudent 类是一个 Room 数据库实体,并且其对应的表名是 my_student

  2. @PrimaryKey(autoGenerate = true):这个注解表明 id 字段是这个实体的主键,并且它的值是自动生成的

  3. @ColumnInfo:这个注解用于描述数据库表中的列信息,它有两个属性,name 表示列名,typeAffinity 表示列的数据类型

  4. @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)的方法
  1. insert(MyStudent... students)@Dao:这个注解表明这个接口是一个 Room 数据库的数据访问对象

  2. delete(MyStudent... students)@Insert:这个注解表明这个方法用于向数据库中插入数据,方法接受一个或多个 MyStudent 对象作为参数,并将它们插入到数据库中

  3. update(MyStudent... students)@Delete:这个注解表明这个方法用于从数据库中删除数据,方法接受一个或多个 MyStudent 对象作为参数,并从数据库中删除它们

  4. getAll()@Update:这个注解表明这个方法用于更新数据库中的数据,方法接受一个或多个 MyStudent 对象作为参数,并更新数据库中对应的记录

  5. getAll()@Query:这个注解用于定义自定义的 SQL 查询,这个方法返回一个 MyStudent 对象的列表,它包含了数据库中所有的学生记录

  6. 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 数据库
  1. entities = {MyStudent.class}:表示这个数据库包含 MyStudent 实体

  2. version = 1:表示数据库的版本号,当实体或数据库结构发生变化时,需要增加这个版本号

  3. 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 注解
  1. Entity 使用的注解
注解说明
@Entity用于标记一个类作为数据库中的表
可以使用 tableName 属性来指定表名
如果类中的字段需要映射到数据库中的列,则字段必须有访问修饰符(public、protected 或默认)
@PrimaryKey用于标记一个字段作为表的主键
可以设置 autoGenerate 为 true 来自动生成主键值
@ColumnInfo用于标记一个字段并提供额外的列信息
可以使用 name 属性来指定列名
可以使用 index 属性来创建索引
@Ignore用于标记一个字段或方法,使其不被 Room 考虑为数据库的一部分
  1. Dao 使用的注解
注解说明
@Dao用于标记一个接口作为数据访问对象(DAO)
DAO 接口中定义的方法用于执行数据库的增删改查操作
Room 会在编译时生成这个接口的实现
@Insert、@Update、@Delete、@Query用于在 DAO 接口中标记方法,分别用于插入、更新、删除和查询数据
@Query 注解允许编写自定义的 SQL 查询语句
  1. 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) {}
}
http://www.lryc.cn/news/603359.html

相关文章:

  • Spring Boot 自动配置:从 2.x 到 3.x 的进化之路
  • 牛顿拉夫逊法PQ分解法计算潮流MATLAB程序计算模型。
  • 微信小程序私密消息
  • GaussDB 数据库架构师修炼(十) 性能诊断常用视图
  • 原生html+js+jq+less 实现时间区间下拉弹窗选择器
  • 鸿蒙网络编程系列59-仓颉版TLS回声服务器示例
  • 42、鸿蒙HarmonyOS Next开发:应用上下文Context
  • Apache Ignite 的分布式原子类型(Atomic Types)
  • 专业Python爬虫实战教程:逆向加密接口与验证码突破完整案例
  • 【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博文章数据可视化分析-文章评论量分析实现
  • Apache Ignite Cluster Groups的介绍
  • U3D中的package
  • 【PHP】Swoole:CentOS安装Composer+Hyperf
  • vue2 使用liveplayer加载视频
  • .NET Core 3.1 升级到 .NET 8
  • 自学嵌入式 day37 HTML
  • 前端代码格式化工具HTML离线版
  • LangChain学习笔记01---基本概念及使用
  • SkSurface---像素的容器:表面
  • echarts饼图
  • .NET测试平台Parasoft dotTEST在汽车电子行业的核心功能及应用
  • OpenAI Python API 完全指南:从入门到实战
  • 使用jQuery动态操作HTML和CSS
  • 从centos更换至ubuntu的安装、配置、操作记录
  • 系统选择菜单(ubuntu grub)介绍
  • 智能健康项链专利拆解:ECG 与 TBI 双模态监测的硬件架构与信号融合
  • Ubuntu22.04系统安装,Nvidia显卡驱动安装问题
  • 【Linux系统编程】Ext2文件系统
  • Java 9 新特性解析
  • VR全景制作流程分享-众趣VR全景制作平台