我在房间数据库类中创建的抽象 Dao 方法出现空指针异常。虽然我提到的几个示例项目做同样的事情,但它的工作原理。我不明白这个实例在其他项目中何时何地被初始化。下面是我的主要活动代码:这是我的应用程序数据库:package com.example.datta.roomtest.Database;import android.arch.persistence.room.Database;import android.arch.persistence.room.Room;import android.arch.persistence.room.RoomDatabase;import android.content.Context;import com.example.datta.roomtest.Dao.PlayerDao;import com.example.datta.roomtest.Entity.Player;@Database(entities = {Player.class},version = 1)public abstract class AppDatabase extends RoomDatabase {private static AppDatabase appDatabase;public static AppDatabase getInstance(Context context){ if(appDatabase!=null){ appDatabase = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database-name").build(); } return appDatabase;} public abstract PlayerDao getPlayerDao();}调用此 getPlayerDao() 方法时,我收到此空指针错误: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.datta.roomtest.Dao.PlayerDao com.example.datta.roomtest.Database.AppDatabase.getPlayerDao()' on a null object reference at com.example.datta.roomtest.MainActivity$DbAsync.doInBackground(MainActivity.java:97) at com.example.datta.roomtest.MainActivity$DbAsync.doInBackground(MainActivity.java:71) at android.os.AsyncTask$2.call(AsyncTask.java:316)
1 回答
守着一只汪
TA贡献1872条经验 获得超3个赞
getInstance() 由于错误的测试总是返回 null:
public static AppDatabase getInstance(Context context){
if(appDatabase!=null){ // <= ERROR HERE, should be == null
appDatabase = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "database-name").build();
}
return appDatabase;
}
添加回答
举报
0/150
提交
取消