I want to show custom dialog with a spinner. Strangely enough, I get NullPointerException when I try to set the adapter of the spinner...
Dialog dialog = new Dialog(this.getApplicationContext());
dialog.setContentView(R.layout.dialog_spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[] {"0","1","2"});
spin = (Spinner)dialog.findViewById(R.id.spinQ);
//What am I doing wrong here?
spin.setAdapter(spinnerAdapter);
dialog.setTitle("Questions");
dialog.show();
The xml layout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:paddingLeft="10dip"
>
<Spinner
android:id="@+id/spinQ"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
UPDATE:
AlertDialog alertDialog;
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_spinner,
(ViewGroup) findViewById(R.id.root));
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {"0","1","2"});
spin = (Spinner) findViewById(R.id.spinQ);
//I get the error in the following line:
spin.setAdapter(spinnerAdapter);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
Your Spinner
is probably not inflated yet. If you want to manipulate the views, inflate it yourself and then use setContentView
on the inflated View
. See the docs on Creating Dialogs.
Update:
In your new code, change:
spin = (Spinner) findViewById(R.id.spinQ);
to:
spin = (Spinner) layout.findViewById(R.id.spinQ);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With