I’ve tryied to use a template (tabbed view activity) in a new project (java).. but it won’t run (no code modifications). Version 2.1.2 on Win 11
error given:
C:ProgettiAndroidTestappsrcmainjavaitgattonerophtestuimainPageViewModel.java:12: error: method map in class Transformations cannot be applied to given types;
private LiveData mText = Transformations.map(mIndex, new Function<Integer, String>() {
^
required: LiveData,Function1<X,Y>
found: MutableLiveData,<anonymous Function<Integer,String>>
reason: cannot infer type-variable(s) X,Y
(argument mismatch; <anonymous Function<Integer,String>> cannot be converted to Function1<X,Y>)
where X,Y are type-variables:
X extends Object declared in method <X,Y>map(LiveData,Function1<X,Y>)
Y extends Object declared in method <X,Y>map(LiveData,Function1<X,Y>)
class
public class PageViewModel extends ViewModel {
private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
@Override
public String apply(Integer input) {
return "Hello world from section: " + input;
}
});
public void setIndex(int index) {
mIndex.setValue(index);
}
public LiveData<String> getText() {
return mText;
}
}
why? I’ve no idea why this template seems to be broken.
2
Answers
As explained in this known issue, the template is generating the code expected by earlier versions of the Lifecycle library. However, that code changed in Lifecycle 2.6.0.
As your error message says, replace
new Function
withnew Function1
, which is the expected class when using Lifecycle 2.6.0 or higher.I converted or replace the
Transformations.map(mIndex, new Function<Integer, String>() {
to lambda.
Since changing it to new Function1 doesn’t work for me.