Search code examples
javakotlinviewmodel

Using Activity ktx with viewmodel and java


I have a piece of code where i need to instantiate my viewmodel using the activity library , i tried to do so in java but nothing seems to be working for me

  • This is the code in kotlin and i want to convert it to java
   mainViewModel : MainViewModel by ViewModels()


Solution

  • In Java, use ViewModelProvider in onCreate method:

    private MainViewModel mainViewModel;
     
    public void onCreate(Bundle savedInstanceState) {
        mainViewModel  = new ViewModelProvider(this).get(MainViewModel.class);
    }
    

    https://developer.android.com/topic/libraries/architecture/viewmodel#implement