调用getResources()时出现空指针异常

时间:2016-11-16 16:01:45

标签: android nullpointerexception

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

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

 --------- 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 个答案:

答案 0 :(得分:10)

您在MainActivity.<init>内过早访问资源,例如字段初始化。您只能在活动生命周期的Context或更高版本中将Resources onCreate()getResources()一起使用。

getStringArray()onCreate()来电移至import Cocoa import IOBluetooth import PlaygroundSupport class BlueDelegate : IOBluetoothDeviceInquiryDelegate { func deviceInquiryComplete(_ sender: IOBluetoothDeviceInquiry, error: IOReturn, aborted: Bool) { aborted print("called") let devices = sender.foundDevices() for device : Any? in devices! { if let thingy = device as? IOBluetoothDevice { thingy.getAddress() } } } } var delegate = BlueDelegate() var inquiry = IOBluetoothDeviceInquiry(delegate: delegate) inquiry?.start() PlaygroundPage.current.needsIndefiniteExecution = true

答案 1 :(得分:0)

对于那些感兴趣的人,我得到了我的代码并运行了以下内容。

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. onCreate()之前的主要活动中声明了三个String []数组。
  2. 初始化资源&#39; res内的onCreate()对象。
  3. getStringArray上调用res以加载每个String []数组

答案 2 :(得分:0)

原来我的问题是我用空的Context实例化了小部件(CardView)。初始化上下文对象可以解决该问题。例如,这是我现在的工作代码,但是当我得到相同的NullPointerException时,m_context为null。

    CardView m_cardView = new CardView(m_context);