我有一个狗的列表,当我从列表中点击特定的狗时,我可以看到详细信息。但是,由于某种原因,文本视图(dogName,dogPurpose,dogLifespan等)未更新。详细信息片段仅显示XML布局给出的默认值。可能是什么问题呢?
class DetailFragment : Fragment() {
private var dogUuid = 0
private lateinit var viewModel: DetailViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
dogUuid = DetailFragmentArgs.fromBundle(it).dogUuid
}
viewModel = ViewModelProviders.of(this).get(DetailViewModel::class.java)
viewModel.fetch(dogUuid)
observeViewModel()
}
private fun observeViewModel(){
viewModel.dogLiveData.observe(this, Observer{ dog ->
dog?.let {
dogName.text = dog.dogBreed
dogPurpose.text = dog.bredFor
dogTemperament.text = dog.temperament
dogLifespan.text = dog.lifeSpan
context?.let {dogImage.loadImage(dog.imageUrl, getProgressDrawable(it))}
}
})
}
}
这是DetailViewModel。
class DetailViewModel(application: Application): BaseViewModel(application) {
val dogLiveData = MutableLiveData<DogBreed>()
fun fetch(uuid: Int){
launch {
val dog = DogDatabase(getApplication()).dogDao().getDog(uuid)
dogLiveData.value = dog
}
}
}
这是我对协程的实现。
abstract class BaseViewModel(application: Application): AndroidViewModel(application), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCleared() {
super.onCleared()
job.cancel()
}
}
似乎从未调用过watchViewModel()中的Observer。为什么?
答案 0 :(得分:0)
您能确认这一行吗
dogLiveData.value = dog
被断点调用?
尝试致电
viewModel.fetch(dogUuid)
之后
observeViewModel()
答案 1 :(得分:0)
添加observeViewModel()
前viewModel.fetch(dogUuid)
class DetailFragment : Fragment() {
private var dogUuid = 0
private lateinit var viewModel: DetailViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
dogUuid = DetailFragmentArgs.fromBundle(it).dogUuid
}
viewModel = ViewModelProviders.of(this).get(DetailViewModel::class.java)
observeViewModel()
viewModel.fetch(dogUuid)
}
private fun observeViewModel(){
viewModel.dogLiveData.observe(this, Observer{ dog ->
dog?.let {
dogName.text = dog.dogBreed
dogPurpose.text = dog.bredFor
dogTemperament.text = dog.temperament
dogLifespan.text = dog.lifeSpan
context?.let {dogImage.loadImage(dog.imageUrl, getProgressDrawable(it))}
}
})
}
}
答案 2 :(得分:0)
问题是我忘记将参数import numpy as np
import tensorflow as tf
w=tf.Variable(0,dtype=tf.float64)
cost=tf.add(tf.add(w**2,tf.multiply(-10,w)),25)
train=tf.keras.optimizers.SGD(0.01).minimize(loss=cost,var_list=w)
init=tf.global_variables_initializer()
session=tf.Session
session.run(init)
print(session.run(w))
for i in range(1000):
session.run(train)
print(session.run(w))
传递到uuid
中,导致DetailFragment
对象在dog
中为空。因此,上面的代码是正确的,问题出在其他地方。