即使条件肯定为真,方法也不会在if语句后返回

时间:2018-07-21 10:07:54

标签: java android methods

每次使用SurfaceView刷新屏幕时,此方法都会在Canvas上呈现一些文本,并且应该在关闭数据库光标(if cursorClosed)时返回。但是,正如您从LogCat中看到的那样,事实并非如此。即使cursorClosed是正确的,如System.out.println(cursorClosed)调用所证明的,它也应该在if语句后应返回时到达此调用。有人可以向我解释为什么会这样吗?谢谢您的所有提示!

这是我的代码:

public void present(float deltaTime) {
        Graphics graphics = game.getGraphics();
        graphics.drawBackground(Assets.background);
        if (cursorClosed)
            return;
        System.out.println(cursorClosed);
        if (picture != null) {
            graphics.drawPixmap(picture, 40, 280, 50);
        }
        if (!translated) {
            graphics.renderText(14, cursor.getString(1), 160, 300);
        } else {
            System.out.println("cursorClosed: " + cursorClosed);
        graphics.renderText(14, cursor.getString(2), 160, 300);
        graphics.drawPixmap(Assets.nextButton, 250, 310, 420);
    }
}

这是LogCat:

07-20 19:21:25.950 21343-21378/com.melonman.wordsandphrases I/System.out: false
07-20 19:21:25.950 21343-21343/com.melonman.wordsandphrases I/System.out: 1
07-20 19:21:25.950 21343-21378/com.melonman.wordsandphrases I/System.out: cursorClosed: true
07-20 19:21:25.950 21343-21378/com.melonman.wordsandphrases E/AndroidRuntime: FATAL EXCEPTION: Thread-35292
Process: com.melonman.wordsandphrases, PID: 21343
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.database.Cursor.getString(int)' on a null object reference
    at com.melonman.wordsandphrases.wordsandphrasesapp.LessonScreen1.present(LessonScreen1.java:83)
    at com.melonman.wordsandphrases.framework.impl.AndroidFastRenderView.run(AndroidFastRenderView.java:46)
    at java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:0)

此代码:

    if (cursorClosed)
        return;
    System.out.println(cursorClosed);

打印false,这就是为什么return语句不执行的原因。

此代码:

    if (!translated) {
        graphics.renderText(14, cursor.getString(1), 160, 300);
    } else {
        System.out.println("cursorClosed: " + cursorClosed);

打印cursorClosed: true