Android app crashes with “Attempt to invoke virtual method on a null object reference”

Tags: ,

I have a “Bottom navigation bar app” with 3 tabs or fragments. On the first fragment I have a PaintView that I can draw on. Drawing works great. But I’m trying to wire up a clear screen function that is invoked via an options menu dropdown. When I select the option to wipe the screen from the options menu, the app crashes with the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.mobile_testapp_android_2.ui.home.PaintView.clearView()' on a null object reference

Here is the code in the file for the options menu:

public class HomeFragment extends Fragment {

    private PaintView paintView;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        PaintView homeFragmentView = new PaintView(requireContext());

        return homeFragmentView;

    //Enable Clear Menu in this fragment
    public void onCreate(@Nullable Bundle savedInstanceState) {

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //inflate menu
        inflater.inflate(, menu);
        super.onCreateOptionsMenu(menu, inflater);
    public boolean onOptionsItemSelected(MenuItem item) {
//Handle menu item clicks here
        int id = item.getItemId();
        if (id == {
            //do clear function here:
            Toast.makeText(getActivity(), "Clear Screen", Toast.LENGTH_SHORT).show();
        return super.onOptionsItemSelected(item);

And here is the code in the PaintView file which contains the clearView() method that I am trying to invoke:

public class PaintView extends View {

    public ViewGroup.LayoutParams params;
    private Path myPath = new Path();
    private Paint brush = new Paint();
    private boolean forceClear;

    public PaintView(Context context) {


        params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    //Clear function
    public void clearView() {
        try {
            forceClear = true;
        } catch (Exception ee) {
            Log.d("Clear Button: ", "We blew up!! " + ee);

I’m thinking that the problem is due to the way that I instantiate the PaintView class in the file, but I don’t get any compilation errors and I can use dot notation paintView.clearView() to access the methods within the PaintView class just fine.

Any tips on what I am doing wrong would be greatly appreciated!

Here are a few screenshots:

First Tab: HomeFragment with Options menu

Options menu item with Clear Screen

Crash dialog after selecting Clear Screen


Try to use the variables, which you define:

// PaintView homeFragmentView = new PaintView(requireContext());
this.paintView = new PaintView(requireContext());

Source: stackoverflow