Null Pointer Exception when calling getResources()

2019-03-06 16:45发布

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++;
    }
}

3条回答
Animai°情兽
2楼-- · 2019-03-06 17:27

My problem turned out to be that I was instantiating my widget (a CardView) with a null Context. Initializing the context object resolved the issue. For example, here is what my working code now looks like, but m_context was null when I was getting the same NullPointerException.

    CardView m_cardView = new CardView(m_context);
查看更多
我命由我不由天
3楼-- · 2019-03-06 17:30

For those that are interested, I got my code up and running with the following.

public class MainActivity extends AppCompatActivity {

    String[] questionHeaders, answerKey, questions;

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

        Resources res = getResources();
        questionHeaders = res.getStringArray(R.array.question_header_array);
        answerKey = res.getStringArray(R.array.answer_key_array);
        questions = res.getStringArray(R.array.questions_array);
    }

    int correctAnswers = 0;
    int questionCounter = 0;
  1. Declared the three String[] arrays in the main activity before onCreate().
  2. Initialize a 'Resources' object named res inside onCreate().
  3. Call getStringArray on res to load each String[] array
查看更多
干净又极端
4楼-- · 2019-03-06 17:32

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.

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

查看更多
登录 后发表回答