简体   繁体   中英

UninitializedPropertyAccessException in Android Studio with viewModel

I'm New to Kotlin and Android Studio and trying to implement Room database with ViewModel now, but I face the problem "kotlin.UninitializedPropertyAccessException: lateinit property habitViewModel has not been initialized"

I think that this is due to the early initialization of View Model, but I can't find the way to fix it.

This is my code below.

Activity OnCreate Code

class HabitActivity: AppCompatActivity() { lateinit var binding: ActivityHabitBinding lateinit var habitViewModel: HabitViewModel lateinit var habitAdapter: HabitAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHabitBinding.inflate(layoutInflater) habitViewModel = ViewModelProvider(this)[habitViewModel::class.java] setContentView(binding.root) // view model habitViewModel.habitList.observe(this) { habitAdapter.update(it) } // adapter habitAdapter = HabitAdapter(this) binding.rvHabitList.layoutManager = LinearLayoutManager(this) binding.rvHabitList.adapter = habitAdapter }

ViewModel code

 class HabitViewModel: ViewModel() { val habitList: LiveData<MutableList<HabitDTO>> private var habitRepository: HabitRepo = HabitRepo.get() init { habitList = habitRepository.list() } }

Build.Gradle dependencies

def arch_version = "2.1.0" def lifecycle_version = "2.5.0-rc02" def roomVersion = "2.4.2" // Room implementation("androidx.room:room-runtime:$roomVersion") kapt("androidx.room:room-compiler:$roomVersion") implementation("androidx.room:room-ktx:$roomVersion") implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' kapt 'org.xerial:sqlite-jdbc:3.34.0' implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")

And This is my error message capture error msg

Your problem is this line, where you try to use an instance of the object you are initializing

habitViewModel = ViewModelProvider(this)[habitViewModel::class.java]

the argument there should be the class name, not the instance name

habitViewModel = ViewModelProvider(this)[HabitViewModel::class.java]

You can also use this syntax instead of the lateinit var approach to get the ViewModel in Kotlin if you have the right -ktx gradle dependencies ( implementation 'androidx.activity:activity-ktx:1.5.0' )

 private val habitViewModel: HabitViewModel by viewModels()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM