LiveData is abstract android

我是研究僧i 提交于 2019-12-10 15:52:53

问题


I tried initializing my LiveData object and it gives the error: "LiveData is abstract, It cannot be instantiated"

LiveData listLiveData = new LiveData<>();


回答1:


Since it is abstract (as @CommonsWare says) you need to extend it to a subclass and then override the methods as required in the form:

public class LiveDataSubClass extends LiveData<Location> {

}

See docs for more details




回答2:


In a ViewModel, you may want to use MutableLiveData instead.

E.g.:

class MyViewModel extends ViewModel {
  private MutableLiveData<String> data = new MutableLiveData<>();

  public LiveData<String> getData() {
    return data;
  }

  public void loadData() {
    // Do some stuff to load the data... then
    data.setValue("new data"); // Or use data.postValue()
  }
}



回答3:


Yes, you cannot instantiate it because it is an abstract class. You can try to use MutableLiveData if you want to set values in the live data object. You can also use Mediator live data if you want to observe other livedata objects.




回答4:


You need to use MutableLiveData and then cast it to its parent class LiveData.

public class MutableLiveData extends LiveData

[MutableLiveData is] LiveData which publicly exposes setValue(T) and postValue(T) method.

You could do something like this:

fun initializeLiveData(foo: String): LiveData<String> {
    return MutableLiveData<String>(foo)
}

So then you get:

Log.d("now it is LiveData", initializeLiveData("bar").value.toString())
// prints "D/now it is LiveData: bar"


来源:https://stackoverflow.com/questions/45624247/livedata-is-abstract-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!