尝试获取现有数据库,Room Android

时间:2018-08-15 11:31:40

标签: android database android-room android-assets

下午好。我在应用程序中建立了一个现有的数据库。我想通过会议室向她讲话,但遇到错误 @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)

Logcat:

{{1}}

1 个答案:

答案 0 :(得分:3)

final AppDatabase db = AppDatabase.getDatabase(getContext());

此行正在重新调整上下文null。上下文尚未附加到片段。如果您在fragment的构造函数中调用getContext(),则会发生这种情况。在onCreateView或onViewCreated()中调用getContext()。

示例代码

 @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment

            Context context = getContext();
            final AppDatabase db = AppDatabase.getDatabase(context);
            return inflater.inflate(R.layout.fragment_profile, container, false);
        }