Spinner в диалоге - NullPointerException - Android - PullRequest
1 голос
/ 06 января 2012

Я хочу показать пользовательский диалог со спиннером в нем.Но когда я делаю, я получаю NullPointerException в методе setAdapter (). Я пытался больше недели и не мог понять, как это сделать правильно.вот мой код:

     AlertDialog alertDialog;

     LayoutInflater inflater = 
                 (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);                          
     View layout = inflater.inflate(R.layout.form,
                                    (ViewGroup) findViewById(R.id.layout_root));

     ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
           android.R.layout.simple_spinner_item, new String[] {"0","1","2"});
     Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //I get the error in the following line:

    try{ 

         spinner.setAdapter(spinnerAdapter);

    }catch(Exception exception){
         Toast.makeText(getApplicationContext(),
    "Exception: "+exception,Toast.LENGTH_SHORT).show();
      }

     AlertDialog.Builder  builder = new AlertDialog.Builder(this);
     builder.setView(layout);
     alertDialog = builder.create();
     alertDialog.setTitle("Security");
     alertDialog.show();
   }

Вот файл xml form.xml:

  ?xml version="1.0" encoding="utf-8"?>


  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   android:id="@+id/layout_root" >


   <Spinner
    android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

  </LinearLayout> 

Пожалуйста, помогите мне.Я перешел по ссылке: Spinner в диалоге - NullPointerException , в которой обсуждается та же проблема, но я все еще не могу это сделать.

Ответы [ 2 ]

2 голосов
/ 06 января 2012

Попробуйте это:

Spinner spinner = (Spinner)layout.findViewById(R.id.spinner1);

2 голосов
/ 06 января 2012

Spinner spinner = (Spinner) findViewById(R.id.spinner1); вы не можете сделать это здесь.Вам нужно использовать layout.findviewById(...).. (надеюсь, у вашего layout_root есть счетчик).

...