Cannot resolve ViewModelProvider construction in a fragment?

Related searches

I have been spending a lot of time trying to figure out why in the code below (towards the end), I get an error on ViewModelProvider(this). I also tried getActivity() instead of 'this', same issue. The error I get is "Cannot resolve constructor ..."

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;



public class ItemSetupFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setup, container, false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ItemSetupFragmentModel model = new ViewModelProvider(this).get(ItemSetupFragmentModel.class);
        model.getKids().observe(this, users -> {
            // update UI
        });
    }
}

Firstly you need to use the latest version of lifecycle extension. It should be:

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0" 

or any updated version.

Then you should use requireActivity() instead of getActivity(). This way you will ensure that the activity is attached an not getting a NullPointerException.

ItemSetupFragmentModel model = new ViewModelProvider(requireActivity()).get(ItemSetupFragmentModel.class);

Note: ViewModel Overview and Declaring Dependencies

I had to restart cache after adding the library to the Gradle file. There is no need to use requireActivity(), this is enough.

Cannot resolve symbol ViewModelProviders on , I didn't have both dependencies in my build, hence the problem. implementation " android.arch.lifecycle:extensions:1.1.0" implementation� ViewModelProvider of (Fragment fragment, ViewModelProvider.Factory factory) Creates a ViewModelProvider, which retains ViewModels while a scope of given fragment is alive. More detailed explanation is in ViewModel. It uses the given ViewModelProvider.Factory to instantiate new ViewModels.

You aren't using the latest library release in which the ViewModelProvider(@NonNull ViewModelStoreOwner owner) constructor was included. You are seeing the latest docs but not using the latest library version of ViewModel. You need to use

    implementation 'androidx.lifecycle:lifecycle-viewmodel:2.2.0' // For Java

or

    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' // For kotlin extension

Cannot resolve symbol ViewModelProviders, Cannot resolve ViewModelProvider construction in a fragment , I also tried getActivity() instead of 'this', same issue. The error I get is "Cannot resolve constructor� @Deprecated @NonNull @MainThread public static ViewModelProvider of(@NonNull Fragment fragment) { return new ViewModelProvider(fragment); } It takes Fragment as an argument, creates ViewModelProvider object and passes the fragment directly to ViewModelProvider constructor. We can use the same way too. E.g. Before:

The cleanest implementation must use Kotlin for its advanced functions. You can either create this kotlin code in a separate Kclass or leave this answer for future users that want to know how to do this in Kotlin. Basically we are initialising the ViewModel by lazy like this:

Make sure you have this dependency:

implementation "androidx.fragment:fragment-ktx:1.2.0"

Create this helper function that accesses an internal fragment-ktx method that allows yo to create a ViewModel instance by lazy:

@MainThread
inline fun <reified VM : ViewModel> Fragment.fragmentViewModel() =
    createViewModelLazy(
        VM::class,
        { this.viewModelStore },
        { ViewModelFactory(Database.getDatabase(requireContext().applicationContext)) }
    )

Now create a ViewModelFactory using this official java example:

https://github.com/android/architecture-components-samples/blob/master/BasicRxJavaSample/app/src/main/java/com/example/android/observability/ui/ViewModelFactory.java

Or, here is the Kotlin variant:

class ViewModelFactory(private val database: Database?) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T {

        requireNotNull(database) { "Database must not be null" }

        return when {

            modelClass.isAssignableFrom(ItemSetupFragmentModel::class.java) -> {
                ItemSetupFragmentModel() as T
            }

            else -> {
                throw IllegalArgumentException("Unknown ViewModel class")
            }
        }
    }
}

And now go inside your fragment and simply initialise your ViewModel like this

class ItemSetupFragment : Fragment() {

    private val model by viewModel<ItemSetupFragmentModel>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        model.getKids().observe(this, users -> {
            // update UI
        });
    }
}

Hope this helps!

Cannot resolve symbol ViewModelProviders on AppCompatActivity, ViewModelProvider(ViewModelStoreOwner, Factory), passing in the fragment those dependencies in your build.gradle file implementation Cannot resolve� Use the 'by viewModels()' Kotlin property delegate or ViewModelProvider.ViewModelProvider(ViewModelStoreOwner, Factory), passing in the fragment and factory. Creates a ViewModelProvider , which retains ViewModels while a scope of given fragment is alive.

You should instantiate your viewModel by :

ItemSetupFragmentModel model = ViewModelProviders.of(this).get(ItemSetupFragmentModel.class);

A default View can be returned by calling Fragment (int) in your constructor. Otherwise, this method returns null. It is recommended to only inflate the layout in this method and move logic that operates on the returned View to onViewCreated (View, Bundle).

Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or an activity), associated with this ViewModelProvider. The created ViewModel is associated with the given scope and will be retained as long as the scope is alive (e.g. if it is an activity, until it is finished or process is killed).

I have a first class extending Fragment, and a second class extending Activity. Android Intent Cannot resolve constructor. Ask Question Asked 6 years, 9 months

And it is because you cannot call ViewModel constructor in Activity or Fragment when you initializing ViewModel and you want to set ViewModel constructor’s argument value so that’s why you need to

Comments
  • What is the error you are getting?
  • Cannot resolve constructor.
  • This is a compilation error.
  • what version of ViewModel in included in build.gradle?
  • Updated answer. You should use the latest version of viewmodel.
  • Thank you. That was it. I had to added those lines to my Gradle.
  • I am having the same code working in one Fragment and Failing in another fragment.
  • Is it for the same problem? Make sure you're using the same fragment class from the same package or something.
  • @Bheen, ViewModelPorviders is deprecated. The doc say to use the constructors for ViewModelProvider directly.