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 HomeFragment.java file for the options menu:

public class HomeFragment extends Fragment {

    private PaintView paintView;

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

        PaintView homeFragmentView = new PaintView(requireContext());

        return homeFragmentView;
    }

    //Enable Clear Menu in this fragment
@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //inflate menu
        inflater.inflate(R.menu.menu_swipes, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//Handle menu item clicks here
        int id = item.getItemId();
        if (id == R.id.action_clearScreen) {
            //do clear function here:
            paintView.clearView();
            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) {
        super(context);

        brush.setAntiAlias(true);
        brush.setColor(Color.MAGENTA);
        brush.setStyle(Paint.Style.STROKE);
        brush.setStrokeJoin(Paint.Join.ROUND);
        brush.setStrokeWidth(8f);

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

    //Clear function
    public void clearView() {
        try {
            forceClear = true;
            invalidate();
        } 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 HomeFragment.java 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

Answer

Try to use the variables, which you define:

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


Source: stackoverflow