我的app数据库类
@Database(entities = {Detail.class}, version = Constant.DATABASE_VERSION)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract FavoritesDao favoritesDao();
public static AppDatabase getAppDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build();
//Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
Gradle自由:
compile "android.arch.persistence.room:runtime:+"
annotationProcessor "android.arch.persistence.room:compiler:+"
当我请求实例时,它会给出这个错误,AppDatabase_Impl不存在
在我的应用课上
public class APp extends Application {
private boolean appRunning = false;
@Override
public void onCreate() {
super.onCreate();
AppDatabase.getAppDatabase(this); //--AppDatabase_Impl does not exist
}
}
使用下面的gradle链接:
compile 'android.arch.persistence.room:runtime:1.0.0-alpha9'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha9'
你需要创建一个不同的单例类,并从那里获取AppDatabase,如下所示:
RoomDB.java
public class RoomDB {
private static RoomDB INSTANCE;
public static AppDatabase getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build();
//Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
App.java
public class App extends Application {
private boolean appRunning = false;
@Override
public void onCreate() {
super.onCreate();
RoomDB.getInstance(this); //This will provide AppDatabase Instance
}
对于那些使用Kotlin的人,尝试在应用程序build.gradle中将annotationProcessor更改为kapt
例如:
// Extensions = ViewModel + LiveData
implementation "android.arch.lifecycle:extensions:1.1.0"
kapt "android.arch.lifecycle:compiler:1.1.0"
// Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
还记得添加这个插件
apply plugin: 'kotlin-kapt'
到应用程序级别构建的顶部。Gradle文件,并做一个清洁和重建(根据https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#6)
在Android Studio中,如果在粘贴代码或构建过程中出现错误,请选择“构建>清洁项目”。然后选择Build > Rebuild Project,然后再次构建。
更新
如果您已经迁移到androidx
def room_version = "2.3.0" // check latest version from docs
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
更新2(自2021年7月起)
def room_version = "2.3.0" // check latest version from docs
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"