Type error on ViewModelProviders#of(Fragment)

merours :

I'm trying to go through the google tutorial on building good ap architecture. I'm using java 8 and SDK 26. Here is the code I have so far :

package test.me;

import android.app.Fragment;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;

public class ChronoFragment extends Fragment {

    private ViewModel my_model;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        my_model = ViewModelProviders.of(this).get(ViewModel.class);  // <-- error on this
        // and so on
    }
}

The trouble is that so far, the SDK returns the following error:

Cannot resolve the method 'of(test.me.ChronoFragment)'.

I don't understand this since

  • ChronoFragment is of type Fragment
  • The method ViewModelProviders#of(Fragment) does exist and is accessible via the sdk.

Any idea on what I'm doing wrong ?

Code-Apprentice :

Architecture Components uses the appcompat Fragment from the support library rather than the native one. Try changing your import for Fragment to

import android.support.v4.app.Fragment;

For historical reasons, there are two different Fragment classes. They have the same functionality but exist in two different packages. For details, see Why are there two Fragment classes in Android?

As of Feb 6, 2019:

Now there is a third Fragment class. If you are using the new AndroidX libraries, then do

import androidx.fragment.app.Fragment;

Be sure you use the correct Fragment class which is consistent with the rest of your dependencies.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=438137&siteId=1