问题
In referring to https://developer.android.com/reference/androidx/lifecycle/SavedStateHandle#getLiveData(java.lang.String,%20T)
The sample codes in Java as below.
String defaultValue = ...; // nullable
LiveData<String> liveData;
if (defaultValue != null) {
liveData = savedStateHandle.get(KEY, defaultValue);
} else {
liveData = savedStateHandle.get(KEY);
}
However, I notice that when tried to compile the code, the statement below is not compilable.
savedStateHandle.get(KEY, defaultValue);
It error out stating
get(String) in SavedStateHandle cannot be applied to (String, java.lang.String).
I trace into the code, and seems like savedStatehandle
doesn't have a get
that takes in a default value. Did I miss anything?
回答1:
Apparently the Google Document has typo. It supposed to be
String defaultValue = ...; // nullable
LiveData<String> liveData;
if (defaultValue != null) {
liveData = savedStateHandle.getLiveData(KEY, defaultValue);
} else {
liveData = savedStateHandle.getLiveData(KEY);
}
i.e. getLiveData
instead of just get
.
来源:https://stackoverflow.com/questions/61166599/viewmodel-savedstatehandler-get-for-livedata-cant-set-default-value-as-per-the