barbo
barbo

Reputation: 5

Android AlertDialog gives the error java.lang.NullPointerException

i need to show a Dialog in my application. In this dialog there is a Spinner. So i use this code to show the dialog and fill the Spinner:

public class setup4 extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setup4);
}

//On bottone setup 4
public void onSetup4bottone(View v)
{
    AlertDialog.Builder customDialog = new AlertDialog.Builder(this);
    customDialog.setTitle("Aggiungi ora scolastica");
    LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view=layoutInflater.inflate(R.layout.aggiungi_ora,null);
    customDialog.setView(view);

    List<String> materie = new ArrayList<String>();
    materie.add("ADASDASD"); materie.add("LOLOLOL");

    Spinner spinner = (Spinner) findViewById(R.id.aggiungi_ora_materia);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, materie);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    customDialog.show();
}
}

onSetup4bottone is the click-event of a simple button that must invoke the Dialog. I can't understand why i get the java.lang.NullPointerException at this line of code:

spinner.setAdapter(adapter);

Thanks for help :)

Upvotes: 0

Views: 492

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502246

Well the obvious candidate is that spinner is null, suggesting that this:

Spinner spinner = (Spinner) findViewById(R.id.aggiungi_ora_materia);

is returning null. The first thing to do is check that - log whether spinner is null.

Are you sure you're using the right ID? As per the docs, findViewById will return null if you use the wrong ID:

Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

Returns
The view if found or null otherwise.

Upvotes: 2

Related Questions