2016-11-16 71 views
-2

我正在爲android做一個測驗程序,並保持東西兼容不同的語言,我已經把我所有的測驗問題和標籤放在我的strings.xml文件中。基本上我需要的功能,是在一個TextView第一個問題顯示,然後當用戶提交他們的答案,它更新到下一個問題。空指針異常調用getResources()

這是我的代碼以及我收到的錯誤消息。

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

回答

7

您正在訪問資源太早,例如MainActivity.<init>例如,字段初始化。您可以在onCreate()或以後在活動週期與Resources只使用你的活動作爲一個Context

移動getResources()getStringArray()調用onCreate()

+0

所以,如果我理解正確此,我應該在「資源RES = res.getStringArray)移動到onCreate()方法? –

+0

一旦我把它們移動到'onCreate',這個數組就不能再被其他類訪問了,那麼我怎樣才能讓這些數組在任何地方都可以訪問? 對不起Noob問題,這是我第一個android應用程序,和我第一次以這種方式使用資源 –

+1

@NeilRuggiero:「一旦我他們搬到的onCreate,陣列不再給班上的其他訪問」 - 離開領域,其中你是。在'super.onCreate()'之後,將**初始化符**移動到'onCreate()'。因此,例如,在'onCreate()'中有'Resources res;'作爲字段,'res = getResources()'。 – CommonsWare

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()之前聲明中的主要活動三個字符串[]數組。
  2. 初始化onCreate()中名爲res的'Resources'對象。在res
  3. 呼叫getStringArray加載每個String []數組