Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModelProvider - .Incomptible type with Fragment

Tags:

java

android

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?

like image 913
mylottofinder.com.au Avatar asked Oct 13 '25 01:10

mylottofinder.com.au


1 Answers

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'
like image 157
AlexeySRG Avatar answered Oct 14 '25 15:10

AlexeySRG