我正在尝试建立一个Room数据库,但是它说Context是空的,即使我在不同的应用程序中尝试了相同的类,它也可以正常工作。
@Database(entities = {City.class, User.class}, version = AppDatabase.DB_VERSION, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
static final int DB_VERSION = 1;
private static AppDatabase INSTANCE;
private static final String DATABASE_NAME = "my_db";
public abstract UserDao userDao();
public abstract CityDao cityDao();
public static AppDatabase getInstance() {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(RoomApp.getAppContext(), AppDatabase.class, DATABASE_NAME)
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}
}
public class RoomApp extends Application {
private static WeakReference<RoomApp> appContext;
@Override
public void onCreate() {
super.onCreate();
appContext = new WeakReference<>(this);
AppDatabase.getInstance(); //this will init & fill db
}
public static Context getAppContext() {
return appContext != null ? appContext.get() : null;
}
}
每当我访问AppDatabase.getInstance();我收到一条错误消息:“无法为数据库提供空上下文。”