0

I have a DrawingView class that extends the View class. In that DrawingView class I have a websocket client defined, where the client recieves a String and divides it into parts where each part will be inserted into an MotionEvent object. Then that object is sent via an onTouchEvent function in the same class and is handled later. So my problem is that the recieved_event is null when using it. Also if I define it locally instead of globally, Android Studio argues that the Object should be set as null. Is there any way to use the recieved_event without getting the null error?

public class DrawingView extends View{

    MotionEvent recieved_event;

    public DrawingView(Context context, AttributeSet attr){
        super(context,attr);
        //the client socket is started
    }
    private final class EchoWebSocketListener extends WebSocketListener {
        private static final int NORMAL_CLOSURE_STATUS = 1000;
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            webSocket.send("Hello!");
        }
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            if(text.contains("!!!!")){
                String[] event_attrs = text.split("!!!!");
                //The recieved_event is null
                recieved_event.setLocation(Float.parseFloat(event_attrs[1]), Float.parseFloat(event_attrs[2]));
                recieved_event.setAction(Integer.parseInt(event_attrs[0]));
                onTouchEvent(recieved_event);
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            webSocket.close(NORMAL_CLOSURE_STATUS, null);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        }
    }
}

The error I get:

Attempt to invoke virtual method 'void android.view.MotionEvent.setLocation(float, float)' on a null object reference
Tomb_Raider_Legend
  • 431
  • 13
  • 29
  • I solved it by initing the object as described in here https://stackoverflow.com/questions/5867059/android-how-to-create-a-motionevent – Tomb_Raider_Legend May 08 '18 at 23:39
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ADM May 09 '18 at 02:52

1 Answers1

0

You must init an object before you start to use it, in this case, your trying to use MotionEvent recieved_event object with the method .setLocation(float, float) before init recieved_event object.

rockar06
  • 454
  • 3
  • 14
  • The only way is to init it as null,since `MotionEvent recieved_event = new MotionEvent()` will case the error `MotionEvent() is not public in android.view.MotionEvent. Cannot be accessed from outside package` – Tomb_Raider_Legend May 08 '18 at 22:30