I am trying to make an AlertDialog that pops up and has a Spinner in it where someone can select an item, and that item is saved to a variable. However, when I'm testing it out, and I click the OK Button, the app stops, and I get a java.NullPointerException
on logcat. Apparently, the Spinner's getSelectedItem()
(which is supposed to get the chosen item) is causing this java.NullPointerException
.
The code that is causing the NullPointerException:
alertDialogBuilder.setView(promptsView);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
final Spinner spinner = (Spinner) findViewById(R.id.LanguagePicker);
/*(error is here) -->*/ text = spinner.getSelectedItem().toString();
spinner.setAdapter(adapter);
String r = textInput.getText().toString();
allTheTranslatedText = getTranslatedText(r);
textOutput.setText(allTheTranslatedText);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
Is there another way you can use retrieve the Spinner's selected item without causing a NullPointerException?