-4

在我的应用程序中,用户可以选择 3 种不同类型的测验。当他们选择一种称为“级别”的测验类型时,我得到一个NullPointerException. “关卡”的算法顺序与游戏类型为“原始”时的顺序相同。您可以在下面的代码中看到这一点。很难解释为什么这些算法是相同的,所以我会省略这些细节,但现在只接受算法是相同的。:)

为什么我会在测验/游戏类型为“级别”时收到此 NPE 异常,但在测验/游戏类型为“原始”时却没有,即使它们的代码/算法相同?

public class QuestionView extends Activity  {

    int correctAnswers = 0;
    int wrongAnswers = 0;
    int answer = 0;
    int i = 0;

    long score = 0;

    long startTime = 20000;
    long interval = 1000;
    long points;

    boolean timerHasStarted = false;

    String category;

    Button answer1, answer2, answer3, answer4;
    TextView question, pointCounter, questionNumber, timeCounter, timeremaining;

    ArrayList<Question> queries;
    public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
    Timer cdTimer;

    ProgressBar bar;

    Context c;

    Singleton singleton = Singleton.getInstance();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.questionview);

        c = this;

        answer1 = (Button)findViewById(R.id.answer1);
        answer2 = (Button)findViewById(R.id.answer2);
        answer3 = (Button)findViewById(R.id.answer3);
        answer4 = (Button)findViewById(R.id.answer4);

        question = (TextView)findViewById(R.id.question);
        questionNumber = (TextView)findViewById(R.id.questionnumber);
        timeremaining = (TextView)findViewById(R.id.timeremaining);

        category = getIntent().getStringExtra("category");
        queries = getIntent().getParcelableArrayListExtra("queries");

        pointsPerQuestion.clear();

        if(singleton.getGameType() == "levels") {

            if(singleton.getLevel() <= 10) {

                cdTimer = new Timer(startTime, interval);
                bar = (ProgressBar)findViewById(R.id.progressbar);
                bar.setIndeterminate(false);
                bar.setMax(20000);

                loadLevelsQuizTen();
            }

            //...

        } else if (singleton.getGameType() == "original") {

            cdTimer = new Timer(startTime, interval);
            bar = (ProgressBar)findViewById(R.id.progressbar);
            bar.setIndeterminate(false);
            bar.setMax(20000);

            loadOriginalQuiz();

        } else if (singleton.getGameType() == "freeplay") {

            loadFreeplayQuiz();

        }
    }

    public void loadFreeplayQuiz() {

        //...

    }

    public void loadLevelsQuizTen() {

        if(i == 10) {

            cdTimer.cancel();
            endQuiz();

        } else {

            if(!timerHasStarted) {
                cdTimer.start();
                timerHasStarted = true;
            } else {
                cdTimer.start();
                timerHasStarted = false;
            }

            //answer = queries.get(i).getCorrectAnswer();  //NULLPOINTEREXCEPTION HERE
            answer = 2;    

            question.setText(queries.get(i).getQuery());  // I COMMENTED OUT ABOVE LINE OF CODE AND NOW NPE IS NOW HERE

            answer1.setText(queries.get(i).getA1());
            answer2.setText(queries.get(i).getA2());
            answer3.setText(queries.get(i).getA3());
            answer4.setText(queries.get(i).getA4());

            answer1.setOnClickListener(new OnClickListener() {
                //...
                }
            });

            answer2.setOnClickListener(new OnClickListener() {
                //...
            });

            answer3.setOnClickListener(new OnClickListener() {
                //...
            });

            answer4.setOnClickListener(new OnClickListener() {
                //...
            });
        } 
    }

    public void loadOriginalQuiz() {

        if(i == 10) {

            cdTimer.cancel();
            endQuiz();

        } else {

            if(!timerHasStarted) {
                cdTimer.start();
                timerHasStarted = true;
            } else {
                cdTimer.start();
                timerHasStarted = false;
            }

            answer = queries.get(i).getCorrectAnswer();

            question.setText(queries.get(i).getQuery());

            answer1.setText(queries.get(i).getA1());
            answer2.setText(queries.get(i).getA2());
            answer3.setText(queries.get(i).getA3());
            answer4.setText(queries.get(i).getA4());

            answer1.setOnClickListener(new OnClickListener() {
                //...
            });

            answer2.setOnClickListener(new OnClickListener() {
                //...
            });

            answer3.setOnClickListener(new OnClickListener() {
                //...
            });

            answer4.setOnClickListener(new OnClickListener() {
                //...
            });
        } 
    }

    public ArrayList<Question> getQueries() {
        return queries;
    }

    public static ArrayList<Long> getPointsPerQuestion() {
        //...
    }

    public void correct() {
        pointsPerQuestion.add(points); 
        score = score + points;
        i++;
        if(singleton.getGameType() == "original") {
            loadOriginalQuiz();
        } else if(singleton.getGameType() == "levels") {
            loadLevelsQuizTen();
        }
    }

    public void incorrect() {
        long zero = 0;
        pointsPerQuestion.add(zero);
        i++;
        loadOriginalQuiz();
    }

    public class Timer extends CountDownTimer {

        public Timer(long startTime, long interval) {
            super(startTime, interval);
        }

        @Override
        public void onFinish() {
            points = 0;
            if(i >= 9) {
                cdTimer.cancel();
                pointsPerQuestion.add(points);
                endQuiz();
            } else {
                wrongAnswers++;
                incorrect();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            bar.setProgress((int) millisUntilFinished);
            points = (millisUntilFinished / 200) + 1;
            timeremaining.setText("Score remaining: " + points);
            if(i < 10) {
                questionNumber.setText(c.getResources().getString(R.string.question) + " " + (i + 1) + " " + c.getResources().getString(R.string.of10));
            }
        }
    }

    public void endQuiz() {
        Intent intent = new Intent(QuestionView.this, Results.class);
        intent.putExtra("correctAnswers", correctAnswers);
        intent.putExtra("wrongAnswers", wrongAnswers);
        intent.putExtra("score", score);
        intent.putExtra("pointsPerQuestion", pointsPerQuestion);
        intent.putParcelableArrayListExtra("queries", queries);
        intent.putExtra("category", category);
        startActivity(intent);
    }

    public void onStop() {
        super.onStop();
    }

    public void onResume() {
        super.onResume();
    }
}

日志猫

06-14 20:44:45.413: E/AndroidRuntime(1335): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.QuestionView}: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.os.Looper.loop(Looper.java:137)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at java.lang.reflect.Method.invokeNative(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at java.lang.reflect.Method.invoke(Method.java:511)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at dalvik.system.NativeStart.main(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335):     at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at matt.lyons.bibletrivia.lite.QuestionView.onCreate(QuestionView.java:80)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.Activity.performCreate(Activity.java:5104)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-14 20:44:45.413: E/AndroidRuntime(1335):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
4

3 回答 3

3

为什么要“接受”?这可能是你论证中的致命缺陷。

这是问题所在:

Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335):     at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)

转到 QuestionView.java 文件中的第 195 行,查看该行上的对象引用,并查看您未能初始化的对象。

你越早停止告诉自己一切都很好,并开始关注真正发生的事情,你就会越早解决问题并继续前进。

您不应该复制任何代码。您应该将它封装在一个方法调用中并在两个地方调用它。这是错误的秘诀。

你还有很多其他问题。您使用私有数据成员 i 以不同的方法做不同的事情。它没有以我能看到的任何方式同步。我看不出为什么该值不能作为方法参数并传入。那会更加线程安全。

当你做这样的事情时,将字符串与 == 进行比较,并复制代码,这会让我怀疑你所做的一切。难怪你有麻烦。投票结束。

于 2013-06-14T20:50:25.587 回答
2

在获取 NPE 的位置设置断点并检查变量的值。我猜要么queries为空(未正确设置或从意图包获取),要么queries.get(i)为空。

于 2013-06-14T20:58:13.747 回答
0

you get the error because you are calling 2 different methods. In levels you call loadLevelsQuizTen();, in original you call loadOriginalQuiz();

Despite the fact you say they are the same, they aren't. I'd use a debugger to step through the method and figure out what is null and why.

于 2013-06-14T20:51:41.470 回答