0
votes

I'm getting a NullPointerException when I tried to instantiate MyViewModel into MyFragment:

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); 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. 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. What should I change to make this work?

Here's how I did my 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:

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();
        }
    }
}
2
Post the error from Logcat - Vishnu

2 Answers

0
votes

Try using this to instantiate the ViewModel

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

Hope this helps. Feel free to ask for clarifications...

0
votes

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:

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, thus the NPE.

So I changed (myDatabase != null) to (myDatabase == null) and that solved it.