Can't access the Fragment View's LifecycleOwner when getView() is null

I am trying to observe a list of all of the exercise names from my ROOM database inside my AlertDialog.

However I am getting the following error message:

java.lang.NullPointerException: Attempt to invoke virtual method '' on a null object reference

The error message is occurring here:

childExerciseViewModel = ViewModelProviders.of((FragmentActivity) context).get(ChildExerciseViewModel.class);                         

How can I avoid the error?


public class AddExerciseDialog extends AppCompatDialogFragment {      private EditText editTextExerciseName;     private ChildExerciseViewModel childExerciseViewModel;     String userEnteredExerciseName;     int exerciseTypeID;     Button cancelBtn;     Button addBtn;     Context context;      @Nullable     @Override     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {          childExerciseViewModel = ViewModelProviders.of((FragmentActivity) context).get(ChildExerciseViewModel.class);         //return view;         return inflater.inflate(R.layout.layout_dialog_add_exercise, container, false);     }      @Override     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {         super.onViewCreated(view, savedInstanceState);          editTextExerciseName = getView().findViewById(;         addBtn = (Button) getView().findViewById(;         cancelBtn = (Button) getView().findViewById(;         addBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 Bundle mArgs = getArguments();                 exerciseTypeID = mArgs.getInt("ExerciseTypeID");                 userEnteredExerciseName = editTextExerciseName.getText().toString();                 childExerciseViewModel.getAllChildExerciseNames().observe((FragmentActivity) context, this::checkIfChildExerciseNameAlreadyExists);                 // this checks if child exercise already exists, if so add error toast             }              private void checkIfChildExerciseNameAlreadyExists(List<String> childExercisesList) {                 for (int i = 0; i < childExercisesList.size(); i++) {                      if (childExercisesList.contains(userEnteredExerciseName)) {                         Toast.makeText(getContext(), "An exercise with that name already exists", Toast.LENGTH_SHORT).show();                     } else {                         final ChildExercises childExercise = new ChildExercises(0, userEnteredExerciseName, null, exerciseTypeID);                         childExerciseViewModel.insert(childExercise);                     }                 }             }         });     } }  
Add Comment
1 Answer(s)

Try this:

use this intead of getViewLifecycleOwner()

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.