Spinner in dialog box - NullPointerException

I want to show a user dialog with a counter. Oddly enough, I get a NullPointerException when trying to install a spinner adapter ...

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(); 

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(); 
+4
source share
1 answer

Your Spinner is probably not overpriced yet. If you want to manipulate views, inflate it yourself, and then use setContentView on an inflated View . See docs in the "Creating Dialogs" section.

Update:

In the new code, change:

 spin = (Spinner) findViewById(R.id.spinQ); 

in

 spin = (Spinner) layout.findViewById(R.id.spinQ); 
+10
source

All Articles