Skip to content
Advertisement

Why does my Android studio App crash when I spam click at the beginning of an activity?

The app works fine if I wait a bit after clicking play, but if I want click on anything clickable right away, the app crashes.

Here is the error message:

JavaScript

Here is my GameView class:

JavaScript

Advertisement

Answer

The call stack

JavaScript

tells you that in the method Joystick.getIsPressed you are trying to convert a Boolean object to a boolean by invoking booleanValue() on it, but that object is null.

You didn’t show the code for Joystick but I suspect it looks something like this:

JavaScript

The important part is that pressed doesn’t get initialised on construction.

If we inspect your GameView.onTouchEvent method you’ll note that setIsPressed is invoked on ACTION_DOWN and ACTION_UP, while isPressed is invoked on ACTION_MOVE.

When you wait a little until the UI is fully initialized ACTION_MOVE will probably always happen after ACTION_DOWN and therefore everything is fine. But when spam clicking it might happen that the ACTION_DOWN event doesn't get forwarded to your view, because it is not ready yet. But ACTION_MOVEis. Now this is the first event you process,pressed` is not yet initialized and you get the NPE you are seeing.

The solution is to either initialize pressed on construction of Joystick or even better: make it a primitive boolean in the first place.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement