这里是我的类,在其中扩展AndroidViewModel的地方,试图通过应用程序构造函数获取数据库上下文,但是当我从MainActivity调用它时,抛出了一个错误,说java.lang.RuntimeException:无法创建类的实例com.example.roomdb33.BookViewModel
public class BookViewModel extends AndroidViewModel {
final BookDAO bookDAO;
public BookViewModel(@NonNull Application application) {
super(application);
BookRoomDB bookDB = BookRoomDB.getDatabse(application);
bookDAO = bookDB.bookDAO();
}
//For Inserting
void insert(BookEntity book){
InsertAsyncTask insertAsyncTask = new InsertAsyncTask(bookDAO);
insertAsyncTask.execute(book);
static class InsertAsyncTask extends AsyncTask<BookEntity,Void,Void>{
final BookDAO bookDAO;
InsertAsyncTask(BookDAO bookDAO) {
this.bookDAO = bookDAO;
}
@Override
protected Void doInBackground(BookEntity... bookEntities) {
bookDAO.insert(bookEntities[0]);
return null;
}
}
}
我的BookRoomDB有一个getDatabase方法,位于
下static BookRoomDB getDatabse(Context context){
if (bookRoomDB == null){
synchronized (BookRoomDB.class){
if (bookRoomDB == null){
bookRoomDB = Room.databaseBuilder(context.getApplicationContext(),BookRoomDB.class,"book_database")
.build();
}
}
}
这是我在MainActivity中打电话的方式
BookViewModel bookViewModel;
bookViewModel = ViewModelProviders.of(this).get(BookViewModel.class);