I have below setup :
MainActivity :
public class MainActivity extends AppCompatActivity {
private MainViewModel mViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
// Adding integer values in ViewModel
mViewModel.selectInteger(1);
mViewModel.selectInteger(10);
mViewModel.selectInteger(111);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow();
}
}
}
MainFragment :
public class MainFragment extends Fragment {
private MainViewModel mViewModel;
private TextView tv;
public static MainFragment newInstance() {
return new MainFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
tv = rootView.findViewById(R.id.myTextView);
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(getActivity()).get(MainViewModel.class);
// I am getting error in below line, Not able to pass List of integer to formatList function
mViewModel.getListOfInt().observe(getActivity(), {value -> {formatList(value)}});
}
private String formatList(List<Integer> list) {
String returnValue = "";
for(Integer a : list) {
returnValue = returnValue + a;
}
return returnValue;
}
}
MainViewModel :
public class MainViewModel extends ViewModel {
// TODO: Implement the ViewModel
private final MutableLiveData<List<Integer>> listOfInt = new MutableLiveData<List<Integer>>();
public MutableLiveData<List<Integer>> getListOfInt() {
return listOfInt;
}
public void selectInteger(Integer a) {
List<Integer> current = listOfInt.getValue();
current.add(a);
listOfInt.setValue(current);
}
}
I am getting error when passing List of integer to formatList()
method.
mViewModel.getListOfInt().observe(getActivity(), value -> {
formatList(value)
});
Hope this helps.