Issue
I'm trying to use ViewModel library in my app, I have created a class MainActivityViewModel
which extends ViewModel class. When trying to instantiate the MainActivityViewModel
class inside MainActivity
by using ViewModelProvider.get(Class)
the get method always results in an unresolved reference
MainActivityViewModel
class:
class MainActivityViewModel: ViewModel() {
private lateinit var mWords: MutableLiveData<List<Word>>
fun getWords(): LiveData<List<Word>>{
return mWords
}
}
MainActivity
class:
class MainActivity : AppCompatActivity() {
private lateinit var mMainActivityViewModel: MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recycler = findViewById<RecyclerView>(R.id.recycler)
recycler.adapter = RecyclerAdapter(this)
recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
mMainActivityViewModel = ViewModelProvider.get(MainActivityViewModel::class.java)
}
} I'm not sure what I'm doing wrong here,
the dependencies used for liveData:
def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"
implementation 'androidx.core:core-ktx:1.3.2'
implementation "androidx.fragment:fragment-ktx:1.2.5"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
Thanks in advance
Solution
You need to pass in context, so ViewModel knows when it can be destoryed.
mMainActivityViewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
Answered By - Shawn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.