简体   繁体   English

Android:在片段中实例化 ViewModel 时出现 NullPointerException

[英]Android: NullPointerException When Instantiating ViewModel in Fragment

I'm getting a NullPointerException when I tried to instantiate MyViewModel into MyFragment:当我尝试将 MyViewModel 实例化为 MyFragment 时出现 NullPointerException:

public class MyFragment extends Fragment {

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        myViewModel = new ViewModelProvider(this, new MyViewModelFactory(
                requireActivity().getApplication(), 0))
                .get(MyViewModel.class);
}

The stack trace seems to be pointing out the last line.get(MyViewModel.class);堆栈跟踪似乎指出了最后一行。get(MyViewModel.class); and I can't get it to work for days now.我现在无法让它工作好几天。 I did null checks on getApplication() by using System.out.println() and a value is returned, so I don't think that is the problem.我使用 System.out.println() 对 getApplication() 进行了 null 检查并返回了一个值,所以我认为这不是问题所在。 This approach that I used worked just fine when I do this on an activity, but when I tried to implement this on a Fragment, a NullPointerException occured.当我在活动上执行此操作时,我使用的这种方法效果很好,但是当我尝试在 Fragment 上实现此操作时,发生了 NullPointerException。 What should I change to make this work?我应该改变什么才能使这项工作?

Here's how I did my ViewModelFactory class:下面是我如何完成我的 ViewModelFactory class:

public class MyViewModelFactory implements ViewModelProvider.Factory {

    private Application application;
    private int intValue;

    public MyViewModelFactory(Application paramApplication, int paramIntValue) {
        application = paramApplication;
        intValue = paramIntValue;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass == MyViewModel.class) {
            return (T) new MyViewModel(application, intValue);
        }
        return null;
    }
}

My ViewModel class:我的 ViewModel class:

public class MyViewModel extends AndroidViewModel {

    private MyDataModelRepository myDataModelRepository;
    private LiveData<List<MyDataModel>> liveDataListMyDataModel;

    public MyViewModel(@NonNull Application application, int intValue) {
        super(application);
        myDataModelRepository= new myDataModelRepository(application);
        if (intValue> 0) {
            liveDataListMyDataModel= myDataModelRepository.getLiveDataListMyDataModelWhere(intValue);
        } else {
            liveDataListMyDataModel= myDataModelRepository.getLiveDataListMyDataModel();
        }
    }
}

Try using this to instantiate the ViewModel尝试使用它来实例化ViewModel

myViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MyViewModel.class);

Hope this helps.希望这可以帮助。 Feel free to ask for clarifications...随时要求澄清...

I just re-investigated my stack trace:我刚刚重新调查了我的堆栈跟踪:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'net.mypackage.DataModel.MyDataModel.MyDataModelDao net.mypackage.DataModel.MySystemDatabase.myDataModelDao()' on a null object reference
        at net.mypackage.DataModel.MyDataModel.MyDataModelRepository.<init>(MyDataModelRepository.java:21)
        at net.mypackage.ViewModel.MyViewModel.MyViewModel.<init>(MyViewModel.java:21)
        at java.lang.reflect.Constructor.newInstance0(Native Method) 
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
        at net.mypackage.View.MyFragment.onViewCreated(MyFragment.java:50)

And figured that my error is most likely coming from my Repository or my Database room class, and when I rechecked the Database class:并认为我的错误很可能来自我的存储库或我的数据库室 class,当我重新检查数据库 class 时:

public static synchronized MyDatabase getInstance(Context context) {
        if (myDatabase != null) {
            myDatabase = Room.databaseBuilder(context.getApplicationContext(),
                myDatabase.class,
                "my_database")
                .fallbackToDestructiveMigration()
                .addCallback(roomCallback)
                .build();
        }
        return myDatabase;
    }

The (myDatabase,= null) is the reason why I'm getting NPE, the instruction in the code is that myDatabase has to be not null before building the database, and since this instance is null at the start, it will never be built at all. (myDatabase,= null) 是我得到 NPE 的原因,代码中的指令是 myDatabase 在构建数据库之前必须不是 null,并且由于这个实例一开始是 null,所以它永远不会被构建一点也不。 thus the NPE.因此 NPE。

So I changed (myDatabase.= null) to (myDatabase == null) and that solved it.所以我将 (myDatabase.= null) 更改为 (myDatabase == null) 并解决了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM