Reputation: 1139
I'm trying to pass data from MainActivity
to SecondActivity
using a MutableLiveData in a ViewModel,, the following code gives me a NullPointerException when SecondActivity tries to access the LiveData
ViewModel:
class MyViewModel: ViewModel() {
val current=MutableLiveData<String>()
}
Main Activity:
class MainActivity : AppCompatActivity() {
private val viewModel: MyViewModel by lazy {
ViewModelProviders.of(this).get(MyViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView.text="test"
viewModel.current.value="test"
textView.setOnClickListener {
startActivity(Intent(this,SecondActivity::class.java))
}
}}
SecondActivity:
class SecondActivity: AppCompatActivity() {
private val viewModel: MyViewModel by lazy {
ViewModelProviders.of(this).get(MyViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
textView2.text = viewModel.current.value!! // NullPointerException
}}
Upvotes: 0
Views: 1439
Reputation: 29280
The viewmodel
in your second Activity
is not the same as that on the 1st Activity
; there is a cache of ViewModel
s by owner (the activities in this case), and these owners are different in each case.
ViewModel
s can be used to share data between Fragment
s on the same Activity
, but they don't work for sharing data between activities. For that, pass the data in the Intent
to start the 2nd Activity
(if lightweight), otherwise store it in some long lived object.
val intent = Intent(this,SecondActivity::class.java).apply {
putExtra("KEY", "<string to pass here>")
}
startActivity(intent)
Upvotes: 2