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
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;
onCreate()
.res
inside onCreate()
.getStringArray
on res
to load each String[] arrayMy 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);
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()
.