I'm following an example of google, the example is in java but when I rewrite it in kotlin I can not instantiate the class. I am learning viewmodel. I have a lot of doubt if I messed up the syntax of my kotlin code.
https://github.com/googlecodelabs/android-room-with-a-view
class 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!!
}