当 getView() 为 null 时无法访问 Fragment View 的 LifecycleOwner

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

我正在尝试从我的 AlertDialog.

中的 ROOM 数据库中观察所有练习名称的列表

但是我收到以下错误消息:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference

此处出现错误消息:

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

如何避免错误?

添加练习对话框

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(R.id.editTextExerciseName);
        addBtn = (Button) getView().findViewById(R.id.addBtn);
        cancelBtn = (Button) getView().findViewById(R.id.cancelBtn);
        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);
                    }
                }
            }
        });
    }
}

试试这个:

使用this代替getViewLifecycleOwner()