web-dev-qa-db-ja.com

クラスのインスタンスを作成できません-ViewModel

私はグーグルの例に従っています、例はJavaにありますが、kotlinで書き直すと、クラスをインスタンス化できません。私はlearningviewmodel。kotlinコードの構文を台無しにしたかどうかは疑問です。

https://github.com/googlecodelabs/Android-room-with-a-view

Error クラスMainActivity:AppCompatActivity(){

//    private lateinit var mWordViewModel: WordViewModel //not works
    private var mWordViewModel: WordViewModel? = null //not works
    private var wordListAdapter: WordListAdapter?= null

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

        try {
            mWordViewModel = ViewModelProviders.of(this@MainActivity).get(WordViewModel::class.Java)
        }catch (e: Exception){
            e.printStackTrace()
        }

.。

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

//    super(application)

    private var mRepository: WordRepository? = null
    private var mAllWords: LiveData<List<Word>>? = null

    init {
        mRepository = WordRepository(application)
        mAllWords = mRepository?.getAllWords()
    }

.。

class WordRepository(application: Application) {

    private var mWordDao: WordDao? = null
    private var mAllWords: LiveData<List<Word>>? = null

    init {
        val db = WordRoomDatabase.getDatabase(application)
        mWordDao = db.wordDao()
        mAllWords = mWordDao!!.getAlphabetizeWords()
    }

.。

@Database(entities = arrayOf(Word::class), version = 1)
abstract class WordRoomDatabase: RoomDatabase(){

    abstract fun wordDao(): WordDao

    companion object {
        @JvmStatic
        private var INSTANCE: WordRoomDatabase? = null

        fun getDatabase(context: Context): WordRoomDatabase {
            if (INSTANCE == null) {
                synchronized(WordRoomDatabase::class.Java) {
                    if (INSTANCE == null) {
                        INSTANCE = Room.databaseBuilder(context.applicationContext, WordRoomDatabase::class.Java, "Word_database")
                                .fallbackToDestructiveMigration()
                                .addCallback(sRoomDatabaseCallback)
                                .build()
                    }
                }
            }
            return INSTANCE!!
        }
4
FlipNovid

@zunjae

エラー

1-構文コードkoltin。

2-プロジェクト構成。

class MainActivity: AppCompatActivity() {
mWordViewModel = ViewModelProviders.of(this@MainActivity).get(WordViewModel(application)::class.Java)

.。

class WordViewModel constructor (application: Application):  AndroidViewModel(application){

.。

class WordRepository constructor(application: Application) {

.。

アプリbuild.gradleを追加します

apply plugin: 'kotlin-kapt'

kapt "Android.Arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
kapt "Android.Arch.persistence.room:compiler:$rootProject.roomVersion"
5
FlipNovid