调用 getResources() 时出现空指针异常 [英] Null Pointer Exception when calling getResources()

查看:29
本文介绍了调用 getResources() 时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 android 制作一个测验程序,并且为了保持对不同语言的兼容,我将所有测验问题和标签放在了我的 strings.xml 文件中.基本上我正在寻找的功能是在 TextView 中显示第一个问题,然后当用户提交他们的答案时,它会更新到下一个问题.

I'm making a quiz program for android, and to keep things compatible for different languages, I've put all my quiz questions and labels in my strings.xml file. Basically the functionality I'm looking for is to have the first question display in a TextView, then when the user submits their answer, it updates to the next question.

这是我的代码以及我收到的错误消息.

Here is my code along with the error message I'm getting.

 --------- beginning of crash
11-16 10:37:21.723 26952-26952/com.example.neil.bsgquiz E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.neil.bsgquiz, PID: 26952
                                                                          java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.neil.bsgquiz/com.example.neil.bsgquiz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2337)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                              at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
                                                                              at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
                                                                              at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:551)
                                                                              at com.example.neil.bsgquiz.MainActivity.<init>(MainActivity.java:28)
                                                                              at java.lang.Class.newInstance(Native Method)
                                                                              at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:148) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5443) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 




package com.example.neil.bsgquiz;

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    int correctAnswers = 0;
    int questionCounter = 0;

    //TODO  Bug seems to be in this section, about getting resources.

    //get question header array from resources
    Resources res = getResources();
    String[] questionHeaders = res.getStringArray(R.array.question_header_array);

    //get answer key array from resources
    String[] answerKey = res.getStringArray(R.array.answer_key_array);

    //get questions from resources
    String[] questions = res.getStringArray(R.array.questions_array);


    public void submitAnswer() {
        //create Edit Text object, and extract user input answer from it
        EditText userAnswerEditText = (EditText) findViewById(R.id.answer_text);
        String userAnswer = userAnswerEditText.getText().toString();

        //compare against answer key and tell user if right or wrong
        if (userAnswer.compareToIgnoreCase(answerKey[questionCounter]) == 0) {
            Toast.makeText(this, "That's Correct!", Toast.LENGTH_SHORT).show();
            correctAnswers++;
        } else {
            Toast.makeText(this, "Sorry, That's Incorrect", Toast.LENGTH_SHORT).show();
        }
        nextQuestion();
    }

    /**
     * @param questionNumber: what question are we getting a hint for
     * @return String containing a hint to give to the user
     */
    private String getHint(int questionNumber) {
        return "0";
    }

    private void nextQuestion() {
        //step forward question header
        TextView headerText = (TextView) findViewById(R.id.question_header);
        headerText.setText(questionHeaders[questionCounter]);

        //step forward question text
        TextView questionText = (TextView) findViewById(R.id.question_text_view);
        questionText.setText(questions[questionCounter]);

        //reset hint for EditText
        EditText userAnswerEditText = (EditText) findViewById(R.id.answer_text);
        userAnswerEditText.setHint("Answer");

        //update correct answer counter
        TextView correctAnswers = (TextView) findViewById(R.id.correct_answer_counter);
        correctAnswers.setText(correctAnswers + " / 8");

        questionCounter++;
    }
}

推荐答案

您在 MainActivity. 中访问资源过早.字段初始化.您只能将您的活动用作 ContextResourcesonCreate() 或活动生命周期的后期.

You're accessing resources too early, in MainActivity.<init> e.g. field initialization. You can only use your activity as a Context with Resources in onCreate() or later in the activity lifecycle.

getResources()getStringArray() 调用移动到 onCreate().

Move the getResources() and getStringArray() calls to onCreate().

这篇关于调用 getResources() 时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆