我的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
}
我也有同样的问题。在一个由Android Studio创建的新示例项目中实现了几个类和接口:
https://developer.android.com/training/data-storage/room/
上面提到的所有解决方案都没有帮助,根据我的数据库类所需的_Impl文件不是由Room生成的。最后,在终端中执行gradle clean build给了我提示,导致解决方案:
警告:没有向注释处理器提供模式导出目录,因此我们不能导出模式。你可以提供空间。schemaLocation注释处理器参数或将exportSchema设置为false。
我在数据库类中添加了参数exportSchema = false
@Database(entities = arrayOf(User::class), version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
然后它工作了,在generatedJava下的app模块中找到了这两个生成的文件:
AppDatabase_Impl
UserDao_Impl
我不理解这种行为,因为参数是可选的,看
https://stackoverflow.com/a/44645943/3258117