首页 > 解决方案 > ViewModelProviders.of(this).get(ViewModel.class) 的 java 错误;

问题描述

我试图在 android studio 中制作一个新片段,每当我构建我的应用程序时,我都会收到此错误:

/Users/****/AndroidStudioProjects/DMSStemApp8/app/src/main/java/com/example/dmsstemapp8/ui/Events/EventsFragment.java:24: error: no suitable method found for get(Class<EventsViewModel>)
                ViewModelProviders.of(this).get(EventsViewModel.class);
                                           ^
    method ViewModelProvider.<T#1>get(Class<T#1>) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: EventsViewModel
        upper bound(s): ViewModel)
    method ViewModelProvider.<T#2>get(String,Class<T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends ViewModel declared in method <T#1>get(Class<T#1>)
    T#2 extends ViewModel declared in method <T#2>get(String,Class<T#2>)

这个错误本身很混乱,我找不到解决方案,所以这也是我的 java 代码

package com.example.dmsstemapp8.ui.Events;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.dmsstemapp8.R;

public class EventsFragment extends Fragment {

    private EventsViewModel EventsViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
        EventsViewModel =
                ViewModelProviders.of(this).get(EventsViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_events);
        EventsViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

如果您需要其他任何东西来解决这个问题,那就问

标签: java

解决方案


确保你

扩展 ViewModel

在您的 EventsViewModel 类中。

这是样本

这是我的课堂样本

public class EventsViewModel extends ViewModel {
.....
}

推荐阅读