算法上的NullPointErexception但是在相同类中的另一个点上没有得到相同算法的NPE

时间:2013-06-14 20:46:33

标签: java android nullpointerexception

在我的应用中,用户可以选择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();
    }
}

logcat的

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)

3 个答案:

答案 0 :(得分: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以不同的方法执行不同的操作。它没有以我能看到的任何方式同步。我认为没有理由为什么这个值不能作为方法参数并传入。这将更加线程安全。

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

答案 1 :(得分:2)

设置断点,获取NPE并检查变量的值。我猜想queries是空的(没有正确设置或从意图包中获取),或queries.get(i)为空。

答案 2 :(得分:0)

您收到错误,因为您正在调用两种不同的方法。在您致电loadLevelsQuizTen();的级别中,原来您致电loadOriginalQuiz();

尽管你说他们是相同的,但事实并非如此。我将使用调试器逐步完成该方法并找出什么是null以及为什么。