问题
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