I wanted to get the selected spinner item in an AlertDialog
. But if I'm trying to print the value with Snackbar
I'm getting a NullPointerException
. How can I refer to the spinner value in the AlertDialog
?
The Exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference.
Dialog's code:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
// Set title of the dialog
builder.setTitle("ToDo hinzufügen");
// Set view to dialog.xml
builder.setView(R.layout.dialog);
// To add ToDos for a specific section
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
// save entry in database and refresh the page
builder.setPositiveButton("Hinzufügen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
Snackbar.make(findViewById(R.id.fab), spinner.getSelectedItem().toString(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:hint="Kategorie auswählen"
android:entries="@array/tab_categeory"
android:spinnerMode="dialog"
/>
<EditText
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Was möchten Sie erledigen?"/>
</LinearLayout>