ava.lang.RuntimeException:无法创建com.example.bookkeepers.BookViewModel类的实例

时间:2019-08-25 10:42:47

标签: android android-viewmodel

我正在开发一本新书的android应用程序,但是当我测试从logcat获取以下异常的代码时,应用程序崩溃

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {com.example.bookkeepers / com.example.bookkeepers.MainActivity}:   java.lang.RuntimeException:无法创建类的实例   com.example.bookkeepers.BookViewModel位于   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)   在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2921)   在android.app.ActivityThread.-wrap11(未知来源:0)处   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1639)   在android.os.Handler.dispatchMessage(Handler.java:106)   android.os.Looper.loop(Looper.java:176)在   android.app.ActivityThread.main(ActivityThread.java:6662)在   java.lang.reflect.Method.invoke(本机方法)位于   com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:547)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)导致   作者:java.lang.RuntimeException:无法创建类的实例   com.example.bookkeepers.BookViewModel位于   androidx.lifecycle.ViewModelProvider $ AndroidViewModelFactory.create(ViewModelProvider.java:208)   在androidx.l

     

ifecycle.ViewModelProvider.get(ViewModelProvider.java:135)在   androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)   在com.example.bookkeepers.MainActivity.onCreate(MainActivity.kt:30)   在android.app.Activity.performCreate(Activity.java:7074)处   android.app.Activity.performCreate(Activity.java:7065)在   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)   在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2796)   ... 9更多原因:java.lang.reflect.InvocationTargetException在   java.lang.reflect.Constructor.newInstance0(本机方法)位于   java.lang.reflect.Constructor.newInstance(Constructor.java:334)在   androidx.lifecycle.ViewModelProvider $ AndroidViewModelFactory.create(ViewModelProvider.java:200)   ... 16更多原因:java.lang.RuntimeException:找不到   com.example.bookkeepers.BookRoomDatabase的实现。   BookRoomDatabase_Impl在以下位置不存在   androidx.room.Room.getGeneratedImplementation(Room.java:94)在   androidx.room.RoomDatabase $ Builder.build(RoomDatabase.java:952)在   com.example.bookkeepers.BookRoomDatabase $ Companion.getDatabase(BookRoomDatabase.kt:24)   在com.example.bookkeepers.BookViewModel。(BookViewModel.kt:12)   ...还有19个

     

在我的BookViewModel类下面,该类扩展了AndroidViewModel类

class BookViewModel(application: Application) : AndroidViewModel(application) {

private val bookDao: BookDao

init {
    val bookDb = BookRoomDatabase.getDatabase(application)

    bookDao = bookDb!!.bookDao()
}


fun insert(book: Book) {
    InsertAsyncTask(bookDao).execute(book)
}

companion object {
    private class InsertAsyncTask(private val bookDao: BookDao) :
        AsyncTask<Book, Void, Void>() {
        override fun doInBackground(vararg books: Book): Void? {
            bookDao.insert(books[0])
            return null
        }

    }
}}

MainActivity.kt下面

MainActivity : AppCompatActivity() {

 lateinit var bookViewModel: BookViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        val intent =  Intent(this, NewBookActivity::class.java)
        startActivityForResult(intent, NEW_NOTE_ACTIVITY_REQUEST_CODE)
    }
   bookViewModel = ViewModelProviders.of(this).get(BookViewModel::class.java)
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == NEW_NOTE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        val id = UUID.randomUUID().toString()
        val authorName = data!!.getStringExtra(NewBookActivity.NEW_AUTHOR)
        val bookName = data!!.getStringExtra(NewBookActivity.NEW_BOOK)

        val book = Book(id, authorName, bookName)
        bookViewModel.insert(book)

        Toast.makeText(
            applicationContext,
            R.string.saved,
            Toast.LENGTH_LONG
        ).show()

    } else {
        Toast.makeText(
            applicationContext,
            R.string.not_saved,
            Toast.LENGTH_LONG
        ).show()
    }
}

companion object{
    private const val NEW_NOTE_ACTIVITY_REQUEST_CODE = 1
}}

在数据库类下面

  @Database(entities = [Book::class], version = 1)
 abstract class BookRoomDatabase :RoomDatabase() {


abstract fun bookDao():BookDao


companion object {

    private var bookRoomInstance:BookRoomDatabase? = null
    fun getDatabase(context: Context): BookRoomDatabase? {
        if (bookRoomInstance == null)
            synchronized(BookRoomDatabase::class.java){
                if(bookRoomInstance == null){
                    bookRoomInstance = Room.databaseBuilder<BookRoomDatabase>(context.applicationContext,
                        BookRoomDatabase::class.java, "book_database")
                        .build()
                }
            }
    return bookRoomInstance
    }

}}

道课以下

@Dao
 interface BookDao {
  @Insert
  fun insert(book: Book)
  }

在图书实体类下方

@Entity(tableName = "books")
class Book(@PrimaryKey val id: String,

       @ColumnInfo(name = "author")
       val author: String,
       val book:String) {
}

2 个答案:

答案 0 :(得分:0)

其背后的想法是,您正在使用kotlin,并且在您的应用#include <boost/spirit/home/x3.hpp> #include <iostream> namespace x3 = boost::spirit::x3; namespace fusion = boost::fusion; using x3::_val; using x3::_attr; using x3::_where; using x3::rule; using fusion::at_c; x3::rule<struct LongHexInt, std::string> const long_hex_int = "long_hex_int"; template <typename T> auto as = [](auto p) { return rule<struct _, T> {} = p; }; auto const long_hex_int_def = x3::lexeme[as<std::string>(x3::string("0") >> +x3::char_('0', '7')) | as<std::string>((x3::digit - '0') >> *x3::digit >> 'u') | as<std::string>((x3::string("0x") | x3::string("0X")) >> +x3::xdigit) | as<std::string>((x3::string("0b") | x3::string("0B")) >> +x3::char_('0', '1'))] ; BOOST_SPIRIT_DEFINE(long_hex_int); int main() { std::string input = R"__(0x12345678ABCDEF)__"; std::string output; if (x3::parse(input.begin(), input.end(), long_hex_int, output)) { std::cout << output; } } 中应该应用kapt插件build.gradle并使用apply plugin 'kotlin-kapt'而不是kapt

annotationProcessor

检查此答案https://stackoverflow.com/a/50487165/4614550

答案 1 :(得分:0)

问题是您试图实例化ViewModel而不提供必需的参数application: Application。 我在这里发布了解决此问题的答案:https://stackoverflow.com/a/65004171/13834895