My Android program used to be working, i used Android studio to get the bottom navigation View Activity. it works. After i run in the actual mobile phone device, it is not working any more, it complains like below:
incompatible types: HomeFragment cannot be converted to ViewModelProviderImpl new ViewModelProvider(this).get(HomeViewModel.class);
the HomeViewModel.java was generated by Andorid studio, after i selected to create the bottom navigation View Activity.
package com.abc.myapplication.ui.home;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class HomeViewModel extends ViewModel {
private final MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home fragment");
}
public LiveData<String> getText() {
return mText;
}
}
My HomeFragment.java shows below, was also generated by Android Studio.
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
// new code
HomeViewModel= new ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textHome;
homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
return root;
}
Would anyone please advise and give me the sample codes as possible?
Rolling back androidx.lifecycle
to version 2.6.1
helped me:
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With