创建的点仍然抛出NullPointerException

时间:2018-10-11 07:24:36

标签: android nullpointerexception point

在我的一个小项目中,我尝试将Point中的Point设置为另一个OnTouchEvent()。这两个点都在构造函数中创建,如下所示:

package com.example.samuel.truespeedgame;

import android.content.Context;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;


public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
        private SurfaceHolder holder;
        private SurfaceViewThread surfaceViewThread;

        public Point clickPoint, playerPoint, startPoint;


        GamePanel(Context context) {
            super(context);

            maxSpeed = 20;

            playerPoint = new Point(200,200); //very normal instanciating of Points i guess
            startPoint = new Point(200,200);
            clickPoint = new Point(200,200);
}

我的OnTouchEvent()如下:

@Override
public boolean onTouchEvent(MotionEvent motionEvent) {

    switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {

        // Player has touched the screen
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
            if(clickPoint != null)
                clickPoint.set((int)motionEvent.getX(),(int)motionEvent.getY());
            else if(clickPoint == null) clickPoint = new Point((int)motionEvent.getX(),(int)motionEvent.getY());

            startPoint = playerPoint; //Here gets the error thrown

            break;

        case MotionEvent.ACTION_UP:

    }
    return true;
}

在重建项目之前,这是 NullPointerException 。现在playerPoint.x.y始终为 0

1 个答案:

答案 0 :(得分:0)

如果不实例化GamePanel,则playerPoint将为null。