使用Room数据库依赖报错

1,931 阅读1分钟

概述

Room 持久性库在 SQLite 的基础上提供了一个抽象层,让用户能够在充分利用 SQLite 的强大功能的同时,获享更强健的数据库访问机制。

今天的问题是出现在依赖项问题, 在应用中使用 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 Room
      implementation "androidx.room:room-ktx:$room_version"

      // optional - RxJava support for Room
      implementation "androidx.room:room-rxjava2:$room_version"

      // optional - Guava support for Room, including Optional and ListenableFuture
      implementation "androidx.room:room-guava:$room_version"

      // Test helpers
      testImplementation "androidx.room:room-testing:$room_version"
    }
    

记录问题

将项目中room数据库由App module迁移到新建的baseLis Module下引入,结果发现initDb出错了,报错信息如下:

Caused by: java.lang.RuntimeException: cannot find implementation for com.lyh.cachelibs.db.Database.AppDatabase. AppDatabase_Impl does not exist

提示AppDatabase_Impl does not exist...

解决问题

经过各种google,在子module下依赖Room,如果我们需要在另一个module下使用Room,我们还需要在你用到Room的模块里也要添加上以下依赖项:

 annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

加入依赖解决问题

分析问题