dentex
dentex

Reputation: 3263

NullpointerException on an inflated View

I have an inflated layout inside an AlertDialog. When I refer to one of its view I get a NullpointerException.

The view with id spinner lies inside the layout dialog_with_spinner.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:padding="20dp">

        <TextView
            android:id="@+id/info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:text="@string/info_title" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:entries="@array/entries" 
            android:saveEnabled="true"/>

    </LinearLayout>

    <CheckBox
        android:id="@+id/someId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/someString"/>

</LinearLayout>

Code:

AlertDialog.Builder builder = new AlertDialog.Builder(boxThemeContextWrapper);
LayoutInflater inflater = getLayoutInflater();

builder.setView(inflater.inflate(R.layout.dialog_with_spinner, null))
       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int id) {

               final Spinner sp = (Spinner) findViewById(R.id.spinner);

               int p = sp.getSelectedItemPosition();  // this gets the **NullPointerException**

               String[] entryValues = getResources().getStringArray(R.array.entry_values);
               final String entry = entryValues[p];

               useMyEntryMethod(entry);
           }
       })
       .setNegativeButton(R.string.dialogs_negative, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               //
           }
       });      

builder.show();

How do I fix this? thanks.

Upvotes: 0

Views: 1200

Answers (1)

user370305
user370305

Reputation: 109247

Replace

final Spinner sp = (Spinner) findViewById(R.id.spinner);

with

final Spinner sp = (Spinner) dialog.findViewById(R.id.spinner);

Access Spinner with dialog's reference for findViewById().

Update:

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_with_spinner, null);
setView(view)

And then Access Spinner using view, Like,

final Spinner sp = (Spinner) view.findViewById(R.id.spinner);

Upvotes: 1

Related Questions