Reputation:
I am a new application developer. I use MaterialBetterSpinner
to displays a set of options for the user. I want to get these options from sting file as getString
.So I do now:
String[] SPINNER_DATA = {getResources().getString (R.string.Small),getResources().getString (R.string.Big)};
MaterialBetterSpinner materialBetterSpinner;
materialBetterSpinner = (MaterialBetterSpinner) findViewById(R.id.material_spinner1);
ArrayAdapter<String> adaptermatr = new ArrayAdapter<String>(AddNewTopic.this, android.R.layout.simple_dropdown_item_1line, SPINNER_DATA);
materialBetterSpinner.setAdapter(adaptermatr);
But I face this problem:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
String class:
<resources>
<string-array name="SPINNER_DATA">
<string name="Small">صغير</string>
<string name="Big">كبير</string>
</string-array>
</resources>
How can I do it?
Upvotes: 2
Views: 75
Reputation: 4039
Please correct your code as below. Move your code to onCreate()
in your Activity. It will solve your Nullpointer
issue.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] SPINNER_DATA = getResources().getStringArray(R.array. SPINNER_DATA);
}
Upvotes: 2
Reputation: 1490
should not be,
// your string file
<resources>
<string name="app_name">whatevr</string>
<string-array name="SPINNER_DATA">
<string name="Small">صغير</string>
<string name="Big">كبير</string>
</string-array>
</resources>
String[] COUNTRIES = getResources().getStringArray(R.array.SPINNER_DATA);
Upvotes: 1