下午好。我在应用中使用一个现有的数据库。我想通过 Room 来操作它,但是我遇到了错误
IllegalArgumentException: Cannot provide null context for the database.
。
我的代码如下: @Database(entities = {Series.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
private static final String DB_NAME = "base.db";
public abstract CymbalDao cymbalDao();
public static AppDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context,
AppDatabase.class, DB_NAME)
.allowMainThreadQueries()
.build();
}
}
}
return INSTANCE;
}
}
数据库位置:
..\src\main\assets\base.db
我希望知道我做错了什么,并听取一些建议,谢谢!
由片段调用:
public class CymbalsFragment extends Fragment {
List<CymbalSeries> cymbalSeries = new ArrayList<>();
CymbalsAdapter cymbalsAdapter;
final AppDatabase db = AppDatabase.getDatabase(getContext());
final CymbalDao cymbalDao = db.cymbalDao();
日志输出:
08-15 15:46:23.247 31769-31769/ru.alexsuvorov.paistewiki W/System.err:
java.lang.IllegalArgumentException: Cannot provide null context for the
database.
08-15 15:46:23.248 31769-31769/ru.alexsuvorov.paistewiki W/System.err: at android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:600)
at ru.alexsuvorov.paistewiki.db.AppDatabase.getDatabase(AppDatabase.java:25)
at ru.alexsuvorov.paistewiki.fragments.CymbalsFragment.<init>(CymbalsFragment.java:29)
at java.lang.Class.newInstance(Native Method)
at ru.alexsuvorov.paistewiki.StartDrawer.onNavigationItemSelected(StartDrawer.java:70)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:154)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at
android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)