Android 空指针异常。语法错误

标签 android eclipse nullpointerexception

我一直在调试下面的代码,这是一个游戏。我的游戏是一个使用拖动的迷宫游戏。在我从其他项目获得一行代码来实现 timer 之前,我的游戏运行良好。

这是我的gameview 的完整代码:

public class GameView extends View {

private TimeCounter timeCounter;

private boolean paused;

public boolean isPaused() {
    return paused;
}

public void setPaused(boolean paused) {
    this.paused = paused;
}    
public void setTimeCounter(TimeCounter timeCounter) {
    this.timeCounter = timeCounter;
}
// width and height of the whole maze and width of lines which
// make the walls
private int width, height, lineWidth;
// size of the maze i.e. number of cells in it
private int mazeSizeX, mazeSizeY;
// width and height of cells in the maze
float cellWidth, cellHeight;
// the following store result of cellWidth+lineWidth
// and cellHeight+lineWidth respectively
float totalCellWidth, totalCellHeight;
// the finishing point of the maze
private int mazeFinishX, mazeFinishY;
private Maze maze;
private Activity context;
private Paint line, red, background;
private String text;

public GameView(Context context, Maze maze) {
    super(context);

    this.context = (Activity) context;
    this.maze = maze;
    mazeFinishX = maze.getFinalX();
    mazeFinishY = maze.getFinalY();
    mazeSizeX = maze.getMazeWidth();
    mazeSizeY = maze.getMazeHeight();
    line = new Paint();
    line.setColor(getResources().getColor(R.color.line));
    red = new Paint();
    red.setColor(getResources().getColor(R.color.position));
    background = new Paint();
    background.setColor(getResources().getColor(R.color.game_bg));
    setFocusable(true);
    this.setFocusableInTouchMode(true);
}

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    width = (w < h) ? w : h;
    height = width; // for now square mazes
    lineWidth = 1; // for now 1 pixel wide walls
    cellWidth = (width - ((float) mazeSizeX * lineWidth)) / mazeSizeX;
    totalCellWidth = cellWidth + lineWidth;
    cellHeight = (height - ((float) mazeSizeY * lineWidth)) / mazeSizeY;
    totalCellHeight = cellHeight + lineWidth;
    red.setTextSize(cellHeight * 0.75f);
    super.onSizeChanged(w, h, oldw, oldh);
}

protected void onDraw(Canvas canvas) {
    canvas.drawRect(0, 0, width, height, background);

    boolean[][] hLines = maze.getHorizontalLines();
    boolean[][] vLines = maze.getVerticalLines();
    // iterate over the boolean arrays to draw walls
    for (int i = 0; i < mazeSizeX; i++) {
        for (int j = 0; j < mazeSizeY; j++) {
            float x = j * totalCellWidth;
            float y = i * totalCellHeight;
            if (j < mazeSizeX - 1 && vLines[i][j]) {
                // we'll draw a vertical line
                canvas.drawLine(x + cellWidth,y,x + cellWidth,y + cellHeight,
                        line);
            }
            if (i < mazeSizeY - 1 && hLines[i][j]) {
                // we'll draw a horizontal line
                canvas.drawLine(x,y + cellHeight,x + cellWidth,y + cellHeight,
                        line);
            }
        }
    }
    int currentX = maze.getCurrentX(), currentY = maze.getCurrentY();
    canvas.drawCircle((currentX * totalCellWidth) + (cellWidth / 2),
            (currentY * totalCellHeight) + (cellWidth / 2),
            (cellWidth * 0.45f), // radius
            red);

    int secondss = timeCounter.getTimeSeconds(); // THIS IS WHERE THE ERROR.

    text = String.format("%02d:%02d", secondss/60, secondss%60);
    canvas.drawText(text, (mazeFinishX * totalCellWidth)
            + (cellWidth * 0.25f), (mazeFinishY * totalCellHeight)
            + (cellHeight * 0.75f), red); 
    }
}

在我从其他项目复制的TimeCounter 类 上使用getTimeSeconds() 方法

public class TimeCounter {
    public int getTimeSeconds() {
        return (int) (getTime() / 1000);
    }
}

logcat:

08-26 16:10:02.516: E/AndroidRuntime(27100): FATAL EXCEPTION: main
08-26 16:10:02.516: E/AndroidRuntime(27100): java.lang.NullPointerException
08-26 16:10:02.516: E/AndroidRuntime(27100):    at com.jforeach.mazegame.GameView.onDraw(GameView.java:129)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.View.draw(View.java:13877)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.View.draw(View.java:13761)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewGroup.drawChild(ViewGroup.java:3039)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2903)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.View.draw(View.java:13759)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewGroup.drawChild(ViewGroup.java:3039)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2903)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.View.draw(View.java:13759)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewGroup.drawChild(ViewGroup.java:3039)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2903)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.View.draw(View.java:13880)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.widget.FrameLayout.draw(FrameLayout.java:467)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2226)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewRootImpl.drawSoftware(ViewRootImpl.java:2719)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewRootImpl.draw(ViewRootImpl.java:2564)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2371)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2172)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1166)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5013)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.Choreographer.doCallbacks(Choreographer.java:579)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.Choreographer.doFrame(Choreographer.java:548)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.os.Handler.handleCallback(Handler.java:725)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.os.Looper.loop(Looper.java:153)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at android.app.ActivityThread.main(ActivityThread.java:5299)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at java.lang.reflect.Method.invokeNative(Native Method)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at java.lang.reflect.Method.invoke(Method.java:511)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-26 16:10:02.516: E/AndroidRuntime(27100):    at dalvik.system.NativeStart.main(Native Method)

更新:在我的菜单上,当单击开始按钮时,它将转到 Game Class,然后是 GameView Class。

这是我的游戏类:

public class Game extends Activity {
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    Maze maze = (Maze)extras.get("maze");
    GameView view = new GameView(this,maze);    
    setContentView(view);

这是我要调用 setTimeCounter 的地方吗?

最佳答案

当你膨胀这个 View 时,它会在你的屏幕上显示 View ,这将调用 onDraw 方法,并在这行代码上:

timeCounter.getTimeSeconds();

它将被调用并抛出异常,因为您甚至还没有实例化该对象。

解决方法:

你需要添加一个 if block 来检查 timeCounter 是否不为 null

示例:

canvas.drawCircle((currentX * totalCellWidth) + (cellWidth / 2),
        (currentY * totalCellHeight) + (cellWidth / 2),
        (cellWidth * 0.45f), // radius
        red);

if(timeCounter != null) {
int secondss = timeCounter.getTimeSeconds(); // THIS IS WHERE THE ERROR.

text = String.format("%02d:%02d", secondss/60, secondss%60);

请记住,如果您使用此 View ,它将直接调用 onDraw,您需要通过它检查对象是否为 null(通过方法调用实例化的对象)

关于Android 空指针异常。语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501096/

相关文章:

android - 在 Testfairy 中上传 apk 时未集成 Testfairy SDK

android - 如何动态设置相对布局背景图片?

java - 有什么方法可以使用 Eclipse 在 Java 字符串文字中编写(复制粘贴)格式良好的 SQL 查询?

Java应用程序内存大小

Android 如何从 InputMethodService 中获取未扩展的 'getCurrentInputConnection()'

java - 使用启动画面启动应用程序,但是当我运行它时

android - GcmListenerService.onMessageReceived 未调用

java - 在 GEF eclipse 中创建数字

java - 由于 AsyncTask onPostExecute(),ArrayAdapter<String> 中出现 Android NullPointerException

java - 使用 Codename One NativeInterface 调用 native Android 库时仍然出现 Nullpointer