Android本地数据存储Room怎么优化

其他教程   发布日期:2025年04月15日   浏览次数:100

本文小编为大家详细介绍“Android本地数据存储Room怎么优化”,内容详细,步骤清晰,细节处理妥当,希望这篇“Android本地数据存储Room怎么优化”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

Room在SQLite基础上做了ORM封装,使用起来类似JPA,不需要写太多的sql。

导入依赖

//room
def room_version="2.4.2"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
//implementation "androidx.room:room-rxjava2:$room_version"
//implementation "androidx.room:room-rxjava3:$room_version"
//implementation "androidx.room:room-guava:$room_version"
//testImplementation "androidx.room:room-testing:$room_version"
//implementation "androidx.room:room-paging:2.5.0-alpha01"

关键注解说明

1、@Database:Room数据库对象。该类需要继承自RoomDatabase,通过Room.databaseBuilder()结合单例设计模式,完成数据库的创建工作。我们创建的Dao对象,在这里以抽象方法的形式返回,只需一行代码即可。

  • entities:指定该数据库有哪些表

  • version:指定数据库版本号,后续数据库的升级正是依据版本号来判断的

2、@Entity:该类与Room中表关联起来。tableName属性可以为该表设置名字,如果不设置,则表名与类名相同。

3、@PrimaryKey:用于指定该字段作为表的主键。

4、@ColumnInfo:设置该字段存储在数据库表中的名字并指定字段的类型;默认字段名和属性名一样

5、@Ignore:忽略该字段

一、使用步骤

1、创建实体类,对应数据库中一张表,使用注解@Entity

2、创建Dao接口类,用于操作数据,使用注解@Dao;不需要实现,在编译的时候,框架会自动生成实现类

3、创建数据库对象Database,继承RoomDatabase,使用单例模式返回实例

4、在Activity中使用,Room数据操作必须在异步线程中执行,所以在Activity中使用线程池执行,或者使用RxJava切换线程

使用代码示例

1、创建实体类,对应数据库中一张表,使用注解@Entity

  1. @Entity
  2. public class Person {
  3. // 主键,自增长
  4. @PrimaryKey(autoGenerate = true)
  5. private int id;
  6. private String name;
  7. private String sex;
  8. private int age;
  9. }

2、创建Dao接口类,用于操作数据,使用注解@Dao;不需要实现,在编译的时候,框架会自动生成实现类

  1. @Dao
  2. public interface PersonDao {
  3. // 插入
  4. @Insert
  5. void insertPersons(Person... persons);
  6. // 修改
  7. @Update
  8. void updatePersons(Person... persons);
  9. // 删除所有
  10. @Query("delete from Person")
  11. void deleteAllPersons();
  12. // 删除指定实体
  13. @Delete
  14. void deletePersons(Person... persons);
  15. // 根据id删除
  16. @Query("delete from Person where id in (:ids)")
  17. void deleteByIds(int ...ids);
  18. // 根据id查询
  19. @Query("select * from Person where id in (:ids)")
  20. List<Person> selectByIds(int ...ids);
  21. // 查询所有
  22. @Query("select * from Person order by id desc")
  23. List<Person> selectAllPersons();
  24. }

3、创建数据库对象Database,继承RoomDatabase,使用单例模式返回实例

  1. @Database(entities = {Person.class}, version = 1)
  2. public abstract class AppDatabase extends RoomDatabase {
  3. public abstract PersonDao personDao();
  4. private volatile static AppDatabase instance;
  5. public static AppDatabase getInstance(Context context){
  6. if (instance == null) {
  7. synchronized (DBHelper.class) {
  8. if (instance == null) {
  9. instance = Room.databaseBuilder(context, AppDatabase.class, "person.db").build();
  10. }
  11. }
  12. }
  13. return instance;
  14. }
  15. }

4、在Activity中使用

Room数据操作必须在异步线程中执行,所以在Activity中使用线程池执行

  1. ExecutorService pool = Executors.newCachedThreadPool();
  2. // 插入数据
  3. public void insertRoom(View view) {
  4. AppDatabase db = AppDatabase.getInstance(getApplicationContext());
  5. pool.execute(() -> {
  6. PersonDao dao = db.personDao();
  7. Person p1 = new Person("用户1", "男", 18);
  8. Person p2 = new Person("用户2", "男", 28);
  9. Person p3 = new Person("用户3", "男", 38);
  10. dao.insertPersons(p1, p2, p3);
  11. });
  12. }
  13. // 查询数据
  14. public void queryRoom(View view) {
  15. AppDatabase db = AppDatabase.getInstance(getApplicationContext());
  16. pool.execute(() -> {
  17. PersonDao dao = db.personDao();
  18. List<Person> list = dao.selectAllPersons();
  19. list.forEach(p-> Log.d("test", p.toString()));
  20. });
  21. }
  22. // 根据id查询
  23. public void queryRoomById(View view) {
  24. AppDatabase db = AppDatabase.getInstance(getApplicationContext());
  25. pool.execute(() -> {
  26. PersonDao dao = db.personDao();
  27. List<Person> list = dao.selectByIds(3,4);
  28. list.forEach(p-> Log.d("test", p.toString()));
  29. });
  30. }
  31. // 删除
  32. public void deleteRoom(View view) {
  33. AppDatabase db = AppDatabase.getInstance(getApplicationContext());
  34. pool.execute(() -> {
  35. PersonDao dao = db.personDao();
  36. dao.deleteByIds(1,2);
  37. });
  38. }

二、类型转换器

SQLite支持null,integer,real,text,blob五种数据类型,实际上SQLite也接受varchar,char,decimal等数据类型,只不过在运算中或保存时会转换成对应的5种数据类型,因此,可以将各种类型数据保存到任何字段中。

除了上述基本类型外,其他如Date、BigDecimal、或Json对象等如何存储呢?

Room给我们提供的非常方便的类型转换器功能。

  • @TypeConverter,定义类型转换静态方法

  • @TypeConverters,定义包含一组转换方法的class类

1、创建类型转换类型,如,Date和Long互转

使用注解@TypeConverter声明具体的转换方法,每个方法必须包含一个参数,以及必须有返回值。

  1. public class DateConverter {
  2. @TypeConverter
  3. public static Date toDate(Long dateLong) {
  4. return dateLong == null ? null : new Date(dateLong);
  5. }
  6. @TypeConverter
  7. public static Long fromDate(Date date) {
  8. return date == null ? null : date.getTime();
  9. }
  10. }

2、将创建好的转换器类,在entity上使用

使用注解@TypeConverters({DateConverter.class}),那么实体类中的所有的Date属性都会被转换成Long存储,查询取出的时候,会自动从Long转换成Date显示。

注意:@TypeConverters放在元素属性、Class、Dao、Database上面

  • 放在元素属性,只对改属性有效

  • 放在实体Class上,对class中所有元素有效

  • 放在Dao上,对Dao的所有方法有效

  • 放在Database,对Database的所有实体和所有Dao都有效

为避免出现混乱,通常建议只在Entity或属性上定义转换器

  1. @Entity
  2. @TypeConverters({DateConverter.class})
  3. public class BsGoods {
  4. private static final long serialVersionUID = 1122172437556010779L;
  5. // 主键
  6. @PrimaryKey
  7. private Long id;
  8. private Date createdDate;
  9. private Date updatedDate;
  10. ...
  11. }

其他类型转换示例,BigDecimal转String。

如果是JavaBean等复杂对象,可以转换成Json字符串存储。

  1. public class BigDecimalConverter {
  2. @TypeConverter
  3. public static String toStr(BigDecimal decimal) {
  4. return decimal == null ? null : decimal.toString();
  5. }
  6. @TypeConverter
  7. public static BigDecimal toDecimal(String str) {
  8. return str == null ? null : new BigDecimal(str);
  9. }
  10. }

三、结合RxJava

在Activity中使用,并且更新界面UI元素

Android的界面UI元素更新,必须在主线程中执行,但是Room的数据查询,又只能使用异常线程处理。那么如何将查询到数据,更新到页面控件上面呢?

这里可以结合RxJava实现流式操作,线下切换!

示例代码,查询所有商品数据,显示在页面控件上面,控件使用的是自定义的TableView,暂不展开,这里只显示数据查询以及显示。

1、在Database类中定义查询方法,传入回调函数

  1. public void selectAll(Consumer<List<BsGoods>> fun) {
  2. BsGoodsDao dao = bsGoodsDao();
  3. Observable.just("select")
  4. .map(s -> dao.selectAll())
  5. .subscribeOn(Schedulers.io())// 给上面的操作分配异步线程
  6. .observeOn(AndroidSchedulers.mainThread())// 给终点分配安卓主线程
  7. .subscribe(new Observer<List<BsGoods>>() {
  8. @Override
  9. public void onSubscribe(@NonNull Disposable d) {
  10. }
  11. @Override
  12. public void onNext(@NonNull List<BsGoods> bsGoods) {
  13. fun.accept(bsGoods);
  14. }
  15. @Override
  16. public void onError(@NonNull Throwable e) {
  17. }
  18. @Override
  19. public void onComplete() {
  20. }
  21. });
  22. }

2、在Activity中使用,传入回调函数更新界面UI

  1. private void initializeTableViewLocal() {
  2. BsGoodsDatabase db = BsGoodsDatabase.getInstance(getContext());
  3. db.selectAll(list -> {
  4. GoodsTableViewModel tableViewModel = new GoodsTableViewModel(list);
  5. TableViewAdapter tableViewAdapter = new TableViewAdapter(tableViewModel);
  6. mTableView.setAdapter(tableViewAdapter);
  7. mTableView.setTableViewListener(new TableViewListener(mTableView));
  8. tableViewAdapter.setAllItems(tableViewModel.getColumnHeaderList(), tableViewModel
  9. .getRowHeaderList(), tableViewModel.getCellList());
  10. });
  11. }

以上就是Android本地数据存储Room怎么优化的详细内容,更多关于Android本地数据存储Room怎么优化的资料请关注九品源码其它相关文章!