使用房间持久性,当试图让数据库插入或在项目中选择时,出现错误:
空对象引用上的AppDataBase.getMovieDao()'
与该过程相关的类如下:
AppDataBase类:
@Database(entities = {Movies.class}, version = 1)
public abstract class AppDataBase extends RoomDatabase {
public static final String DB_NAME = "Movies";
private static AppDataBase INSTANCE;
public static AppDataBase getDataBase(Context context){
if (INSTANCE == null){
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),AppDataBase.class,DB_NAME).build();
}
return INSTANCE;
}
public abstract MovieDao getMovieDao();
}
道上课:
@Dao
public interface MovieDao {
@Insert
void insertAll(Movies movies);
@Update
void updateAll(Movies... notes);
@Query("SELECT * FROM moviestb")
List<Movies> getAll();
@Delete
void deleteAll(Movies... notes);
}
实体类:
@Entity(tableName = "moviestb")
public class Movies {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "idmovie")
private long id;
@ColumnInfo(name = "titlemovie")
private String titlemovie;
........
}
搜索注册:
public void loadFromDB(){
db.getDataBase(view.getContext());
if(db.getMovieDao().getAll().size() > 0){
adapter.setResults(db.getMovieDao().getAll());
}else{
Toast.makeText(view.getContext(),"Não há filmes cadastrados",Toast.LENGTH_SHORT).show();
view.getActivity().finish();
}
}
插入:
public View.OnClickListener onSaveClick(final String plot, final String diretor, final String autor,
final String nome, final String tipo, final String ano, final String ator, final String imdb) {
return new View.OnClickListener() {
@Override
public void onClick(View itemView) {
db.getDataBase(view.getContext());
Movies movies = new Movies(nome,plot,imdb,"",ator,ano,tipo,diretor,autor);
new InsertAsyncTask(db).execute(movies);
}
};
}
private class InsertAsyncTask extends AsyncTask<Movies,Void,Void>{
private AppDataBase db;
public InsertAsyncTask(AppDataBase appDataBase) {
db = appDataBase;
}
@Override
protected Void doInBackground(Movies... params) {
db.getMovieDao().insertAll(params[0]);
return null;
}
}
全部搜索:
public void loadFromDB(){
db.getDataBase(view.getContext());
if(db.getMovieDao().getAll().size() > 0){
adapter.setResults(db.getMovieDao().getAll());
}else{
Toast.makeText(view.getContext(),"Não há filmes cadastrados",Toast.LENGTH_SHORT).show();
view.getActivity().finish();
}
}
在获取数据库时发生崩溃,我做错了什么?谢谢!
答案 0 :(得分:0)
db
是null
。您的问题没有显示您为其指定值的位置。
请注意,getDataBase()
是一种static
方法。也许你应该在某处发表db=AppDataBase.getDataBase()
声明。