无法在我的活动中初始化Room DB

时间:2018-01-24 06:48:20

标签: java android android-room

我有一个数据库:

@Database(entities = {Bas.class, Cit.class}, version = 1)
public abstract class DB extends RoomDatabase {

    private static final String DB_NAME = "db";

    private static DB Database;



    public static DB getDatabase(Context context){

        if (Database == null){
            Database = Room.databaseBuilder(context, Database.class, DB_NAME)

                    .build();
        }

        return Database;





    }

2 个答案:

答案 0 :(得分:2)

修改数据库类

  

使用同步关键字

private static DB sInstance;

public static DB getDatabase(final Context context) {
    if (sInstance == null) {
        synchronized (DB.class) {
            if (sInstance == null) {
                sInstance = Room.databaseBuilder(context, DB.class, DB_NAME)
                        .build();
            }
        }
    }
    return sInstance;
}

并在活动中初始化数据库:

DB db = DB.getDatabase(getApplicationContext());
  

别忘了在app.gradle中定义房间相关性:

implementation "android.arch.persistence.room:runtime:LatestVersion"

annotationProcessor "android.arch.persistence.room:compiler:LatestVersion"

答案 1 :(得分:0)

我刚刚改变了

annotationProcessor "android.arch.persistence.room:compiler:VERSION"

kapt "android.arch.persistence.room:compiler:VERSION" 

并解决了它