简体   繁体   中英

How to fill spinner from string file in android

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?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM