简体   繁体   English

即使在postValue()Kotlin之后,MutableLiveData ArrayList也为空

[英]MutableLiveData ArrayList is empty even after postValue() Kotlin

I am now stuck and currently wondering why my mutable arraylist returns null even if it is being updated with postvalue(). 我现在陷入困境,目前想知道为什么我的可变数组列表即使使用postvalue()更新也返回null。 I tried to display it using Toast and it displayed [] which I think is null. 我尝试使用Toast显示它,并且显示[],我认为它为null。 It had no space in between so it looked like a box. 它之间没有空间,所以看起来像一个盒子。 I did toString() it as well in order to show the text. 我也做了toString()以便显示文本。 How would I be able to solve this problem? 我将如何解决这个问题?

Here is my Main Activity: 这是我的主要活动:

val list = ArrayList<String>()
list.add("text1")
list.add("text2")
val viewmodel = ViewModelProviders.of(this).get(viewmodel::class.java)
viewmodel.Testlist.postValue(list)

ViewModel: 视图模型:

class viewmodel: ViewModel() {
    val Testlist: MutableLiveData<ArrayList<String>> = MutableLiveData()
    init {
        Testlist.value = arrayListOf()
    }
}

Fragment: 分段:

Top area: 顶部区域:

activity?.let {
    val viewmodel = ViewModelProviders.of(this).get(viewmodel::class.java)
    observeInput(viewmodel)
}

Bottom area: 底部区域:

private fun observeInput(viewmodel: viewmodel) {
    viewmodel.Testlist.observe(viewLifecycleOwner, Observer {
        it?.let {
            Toast.makeText(context, it.toString(), Toast.LENGTH_LONG).show()
        }
    })
}

have you used the same instance of your view model? 您是否使用过相同的视图模型实例? or have you defined another view model in the fragment class? 还是在fragment类中定义了另一个视图模型? The issue could be that you're accessing a different instance of the view model and not the one were the MutableLiveData was updated 问题可能是您正在访问视图模型的另一个实例,而不是MutableLiveData已更新的那个。

You can use this : 您可以使用:

    fun <T : Any?> MutableLiveData<ArrayList<T>>.default(initialValue: ArrayList<T>) = apply { setValue(initialValue) }

and then use this function as below: 然后使用以下功能:

    viewmodel.Testlist.default(ArrayList())

For me, I have a BaseActivity that other activities extend from it : 对我来说,我有一个BaseActivity,其他活动也可以从中扩展:

class UAppCompatActivity : AppCompatActivity() {

    protected fun <T : Any?> MutableLiveData<ArrayList<T>>.default(initialValue: ArrayList<T>) = apply { setValue(initialValue) }

    protected fun <T> MutableLiveData<ArrayList<T>>.addItem(item: T) {
        val updatedItems = this.value as ArrayList
        updatedItems.add(item)
        this.value = updatedItems
    }

    protected fun <T> MutableLiveData<ArrayList<T>>.deleteItem(item: T) {
        val updatedItems = this.value as ArrayList
        updatedItems.remove(item)
        this.value = updatedItems
    }

    ...

You post the value to the LiveData object in the activity's viewmodel , which isn't the same instance as the fragment's viewmodel . 您将值发布到活动的viewmodelLiveData对象中,该实例与片段的viewmodel Let's take look at the way you instantiate the viewmodel in your fragment: 让我们看一下在片段中实例化viewmodel的方式:

activity?.let {
    // activity can be refered by the implicit parameter `it`
    // `this` refers to the current fragment hence it's the owner of the view model
    val viewmodel = ViewModelProviders.of(this).get(viewmodel::class.java)
    observeInput(viewmodel)
}

To get a viewmodel that is shared between your activity and fragment you have to pass the activity as its owner: 要获得在活动和片段之间共享的viewmodel ,您必须以活动的所有者身份传递活动:

activity?.let { val viewmodel = ViewModelProviders.of(it).get(viewmodel::class.java) }

Probably you can see developer guide example to resolve your problem 可能您可以看到开发人员指南示例来解决您的问题

https://developer.android.com/topic/libraries/architecture/viewmodel.html#kotlin https://developer.android.com/topic/libraries/architecture/viewmodel.html#kotlin

// shared viewmodel //共享的viewmodel

 class SharedViewModel : ViewModel() {
    private val usersList: MutableLiveData<List<String>>()

    fun getUsers(): LiveData<List<String>> {
        return usersList
    }

    fun setUsers(users: List<String>) {
        usersList.value = users
    }
 }

// Attach ViewModel In Activity onCreate() //在活动onCreate()中附加ViewModel

val model = ViewModelProviders.of(this)[SharedViewModel::class.java]

val list = arrayListOf<String>()
list.add("user1")
list.add("user2")

model.setUsers(list)

// Get same ViewModel instance In fragment onCreateView() //在片段onCreateView()中获取相同的ViewModel实例

model = activity?.run {
        ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")

model.getUsers().observe(this, Observer<List<User>>{ users ->
      // update UI
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UnitTest中的MutableLiveData上的setValue和postValue - setValue and postValue on MutableLiveData in UnitTest MutableLiveData 中 setValue() 和 postValue() 的区别 - Difference of setValue() & postValue() in MutableLiveData 转换 ArrayList<model> 到 MutableLiveData <arraylist<model> &gt; 在 Kotlin </arraylist<model></model> - Convert ArrayList<Model> to MutableLiveData<ArrayList<Model>> in Kotlin MutableLiveData的postValue方法返回null - postValue Method of MutableLiveData returning null Kotlin 协程:尝试在 null ZA8CFDE6331BD59EB2AC96F8911C4B66 上调用虚拟方法 'void androidx.lifecycle.MutableLiveData.postValue(java.lang.Object)' - Kotlin coroutines: Attempt to invoke virtual method 'void androidx.lifecycle.MutableLiveData.postValue(java.lang.Object)' on a null object reference 在 Kotlin 中使用 Volley 后清空 ArrayList - Empty ArrayList after using Volley in Kotlin postValue() 不会在 MutableLiveData 上调用观察 - postValue() doesn't call observe on MutableLiveData 在不使用 postValue() 的情况下调用 MutableLiveData Observer - Invoke MutableLiveData Observer without using postValue() ArrayList 即使在添加元素后也显示为空 - ArrayList showing empty even after adding elements 为什么在没有 postValue 的情况下观察 Mu​​tableLiveData 触发两次? - Why observe MutableLiveData triggers twice without postValue?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM