Search code examples
androidviewmodelandroid-jetpackandroid-viewmodel

Not able to access value of ViewModel's List<Integer>


I have below setup :

  • Single MainActivity holding a MainFragment
  • MainActivity has ViewModel which stores List of Integers
  • MainActivity writes integer values in this ViewModel
  • I want to print these values in MainFragment
  • I am able to access ViewModel instance but not able to get List value from this instance

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.

enter image description here


Solution

  •  mViewModel.getListOfInt().observe(getActivity(), value -> {
    
         formatList(value)
     });
    

    Hope this helps.