Question

The question is quite obvious but still none of them help me to solve. I'm using a spinner that need to filled with string by array adapter. But while running application, null pointer exception occurred. Also i've declared spinner and ArrayAdapter<String> as global variable and defined it in onCreate method. But still its showing null pointer exception. Could anyone please have a look at my code to see what the problem is and how to fix it. Thanks in advance.

Here's my code:

String elements[] ={"- Select -","Iron", "Bronze", "Magnesium"};
Spinner fSpinner;
ArrayAdapter<String> adp;

in onCreate :

fSpinner =(Spinner)findViewById(R.id.fSpinner);
    adp = new ArrayAdapter<String> (MainActivity.this, android.R.layout.simple_spinner_dropdown_item,elements);
    fSpinner.setAdapter(adp);

logcat

Was it helpful?

Solution

this is working for me

List<String> elements=new ArrayList<String>();
elements.add("- Select -");
elements.add("Iron");
ArrayAdapter<String> adapt= new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, elements);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapt);

OTHER TIPS

ArrayAdapter<Charsequence> adt= new ArrayAdapter<Charsequence>(this,android.R.layout.simple_spinner_item, list);
        adt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

Make necessary changes and try the above code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top