Null Pointer Exception when calling getResources()

前端 未结 3 677
长情又很酷
长情又很酷 2021-01-17 06:08

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

相关标签:
3条回答
  • 2021-01-17 06:32

    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
    0 讨论(0)
  • 2021-01-17 06:36

    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);
    
    0 讨论(0)
  • 2021-01-17 06:44

    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().

    0 讨论(0)
提交回复
热议问题