Room学习

文档主页https://developer.android.google.cn/training/data-storage/room

添加依赖

    def room_version = "2.4.3"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

Room 包含三个主要组件:

  • 数据库类,用于保存数据库并作为应用持久性数据底层连接的主要访问点。
  • 数据实体,用于表示应用的数据库中的表。
  • 数据访问对象 (DAO),提供您的应用可用于查询、更新、插入和删除数据库中的数据的方法。
@Database(
        //entities 表示这个数据库中包含哪些表
        entities = {
                FavoriteEntity.class, DeleteEntity.class
        },
        //为什么要改版本   表结构变化了就要更新版本
        version = 3,
        //是否导出(添加吧)
        exportSchema = false
)
public abstract class AppDatabase extends RoomDatabase {

    /**
     * 获取数据访问对象
     */
    public abstract FavoriteDao favoriteDao();

    public abstract DeleteDao deleteDao();

    private static AppDatabase database;

    public static void init(Context context) {
        database = Room.databaseBuilder(context, AppDatabase.class, "AppDatabase.db")
                //这个是 允许主线程访问数据库 (必加)
                .allowMainThreadQueries()
                //当数据库版本更新了,删除之前的数据库,重新创建数据库
                .fallbackToDestructiveMigration()
                .build();
    }

    public static AppDatabase getDatabase() {
        return database;
    }
}

/**
 * Dao
 * ORDER BY 关键字用于对结果集进行排序。
 * SELECT 语句用于从数据库中选取数据。  SELECT column_name,column_name  FROM table_name;    SELECT * FROM table_name;
 */
@Dao
public interface DeleteDao {

    /**
     * 返回值可以是一个LiveData
     * 当数据库中的数据变化了,LiveData就会更新
     * 按删除时间降序排序
     */
    //todo 琢磨为啥要LiveData,以后自己怎么用
    @Query("SELECT * FROM DeleteEntity order by timestamp desc")
    LiveData<List<DeleteEntity>> loadAll();

    /**
     * 查询数量
     */
    @Query("SELECT count() FROM DeleteEntity order by timestamp desc")
    int loadCount();

    /**
     * 查询第一个
     */
    @Query("SELECT * FROM DeleteEntity order by timestamp desc limit 1")
    DeleteEntity loadFirst();

    @Query("SELECT id FROM DeleteEntity")
    List<Integer> getAllId();

    @Query("SELECT * FROM DeleteEntity WHERE id = :id")
    DeleteEntity loadById(int id);

    /**
     * 添加 删除记录
     * @param entity   删除的entity
     * onConflict:表示数据冲突时的处理策略      REPLACE:表示覆盖数据
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void addRecord(DeleteEntity entity);

    /**
     * 删除 删除记录(根据id)
     * @param id
     */
    @Query("DELETE FROM DeleteEntity WHERE id = :id")
    void deleteRecord(int id);
}

LiveData的使用

1.从数据库得到LiveData的数据

 2.观察observeForever()这个数据

private final LiveData<List<DeleteEntity>> mAllCollect;

 public PhotoViewModel(@NonNull Application application) {
        super(application);
        //先得到所有收藏的数据(为观察收藏数据做一个基础数据)
        allCollectId = mCollectionRepository.getAllCollectId();
        //一直观察收藏的数据
        //添加观察的时候,就会收到数据更新
        allCollectId.observeForever(mCollection);

        mAllCollect = mDeleteRepository.getAllCollect();
        mAllCollect.observeForever(mDelete);


        mContentObserver.register(getApplication());


    }

    /**
     * 观察删除的数据
     */
    Observer<List<DeleteEntity>> mDelete = new Observer<List<DeleteEntity>>() {
        @Override
        public void onChanged(List<DeleteEntity> deleteEntities) {

            List<PhotoEntity> allPhotoAndVideo = getAllPhotoAndVideo();

            //重写给图片新的值
            mPhotoData.postValue(allPhotoAndVideo);
        }
    };

3.在onCleared()里移除观察者removeObserver() 

 @Override
    protected void onCleared() {
        super.onCleared();
        //因为是observeForever,所有需要移除
        allCollectId.removeObserver(mCollection);

        mAllCollect.removeObserver(mDelete);

        mContentObserver.unRegister(getApplication());
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值