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?
Do like this.
You are missing promptsView.findViewById();
final Spinner spinner = (Spinner) promptsView.findViewById(R.id.LanguagePicker);
View promptsView = LayoutInflator.inflator(......//do it);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//this is the main line
final Spinner spinner = (Spinner) promptsView.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();
}
});
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.