1

我正在尝试制作一款 Android 游戏,并且我正在关注一些代码示例以使我的游戏循环正常工作。它涉及制作一个新线程。在该run()方法中,我有一个 try/finally 块。在 finally 块执行后NullPointerException会抛出一个。我不知道为什么,似乎没有什么是空的,即使是空的,也没有什么引用任何空的。我以为可能this是空的,但似乎不是。这是我认为相关的代码:

public class MainThread extends Thread {
private boolean running;
private final SurfaceHolder holder;

private boolean GameIsRunning = false;

private int mMode;
public static final int STATE_LOSE = 1;
public static final int STATE_PAUSE = 2;
public static final int STATE_READY = 3;
public static final int STATE_RUNNING = 4;
public static final int STATE_WIN = 5;

private MainGame game;

public MainThread(SurfaceHolder holder, MainGamePanel panel) {
    super();
    this.holder = holder;
    game = new MainGame(panel.getContext());
    mMode = STATE_RUNNING;
}

@Override
public void run() {
    while (running) {
        Canvas c = null;
        try {
            c = holder.lockCanvas(null);
            synchronized (holder) {
                if (mMode == STATE_RUNNING) {
                    updateAll();
                }
                drawAll(c);
            }
        } finally {
            // do this in a finally so that if an exception is thrown
            // during the above, we don't leave the Surface in an
            // inconsistent state
            if (c != null) {
                holder.unlockCanvasAndPost(c);
            }
        } // <<<<<<<<<<<<< After this line executes a null pointer exception is thrown
    } 
}

线程的创建:

public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback{

private MainThread thread;

public MainGamePanel(Context context) {
    super(context);
    getHolder().addCallback(this);

    // create the game loop thread
    thread = new MainThread(getHolder(), this);
    setFocusable(true);
}


@Override
public void surfaceCreated(SurfaceHolder holder) {
    thread.setRunning(true);
    thread.start();
}

谢谢!

4

2 回答 2

4

NPE 被抛出到 try 块中,并在 finally 块执行后变得可见。

从查看代码来看,它最有可能发生,因为cnull你将它传递给updateAll. 您null在 finally 块中有一个检查 - 所以我猜您希望它可能为空。在 try 块中添加另一个检查并在c == null那里处理。


从安卓 API ( SurfaceHolder#lockCanvas):

如果表面尚未创建或无法编辑,则返回null

于 2011-05-27T07:01:46.833 回答
-1

尝试替换c = holder.lockCanvas(null);c = holder.lockCanvas();

当然,您应该发布您的堆栈跟踪。

于 2011-05-27T07:03:47.437 回答