在alertDialog中使用微调器时出现空指针异常

时间:2012-06-07 04:12:22

标签: android nullpointerexception spinner alertdialog

这是我写的代码:

// create a view in dialog box
final View fileView = getLayoutInflater().inflate(R.layout.filename, null);
String[] array_spinner = new String[5];
array_spinner[0]="1";
array_spinner[1]="2";
array_spinner[2]="3";
array_spinner[3]="4";
array_spinner[4]="5";

Spinner s = (Spinner) findViewById(R.id.sp_CAT);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
s.setSelection(2);

//Spinner mCAT = (Spinner) findViewById(R.id.sp_CAT);
//ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
//fileView.getContext(), R.array.a_CAT, android.R.layout.simple_spinner_item);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//mCAT.setAdapter(adapter);

EditText mSID = (EditText) fileView.findViewById(R.id.et_SID);
EditText mSCD = (EditText) fileView.findViewById(R.id.et_SCD);
EditText mNUM = (EditText) fileView.findViewById(R.id.et_NUM);
final String tSID=mSID.getText().toString();
final String tSCD=mSCD.getText().toString();
final String tNUM=mNUM.getText().toString();

// show dialog box
new AlertDialog.Builder(CameraActivity3.this).setTitle("Set FileName")
  .setView(fileView)
  .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {

      Toast.makeText(CameraActivity3.this, tSID+tSCD+tNUM, Toast.LENGTH_SHORT).show();

    }// public void onClick
  }) // setPositiveButton
  .setNegativeButton("Cancel", null).show();

但是,我收到空指针异常。经过一些测试(注释掉一些行),它似乎与微调器适配器有关。我弄错了吗?

3 个答案:

答案 0 :(得分:5)

使用此:

Spinner s = (Spinner) fileView.findViewById(R.id.sp_CAT);

答案 1 :(得分:2)

写下面的代码行

Spinner s = (Spinner) fileView.findViewById(R.id.sp_CAT);

而不是

Spinner s = (Spinner) findViewById(R.id.sp_CAT);

答案 2 :(得分:1)

对于将来使用DialogFragment构建AlertDialog的人来看,您不能仅在this中使用ArrayAdapter。我的解决方案如下:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View myView = inflater.inflate(R.layout.program_num_spinner_popup, null);

    builder.setView(myView);

    programNumbers = (Spinner) myView.findViewById(R.id.prog_num_spinner_list);
    ArrayAdapter<CharSequence> numbersAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.program_numbers, android.R.layout.simple_spinner_item);
    numbersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    programNumbers.setAdapter(numbersAdapter);

我将this替换为this.getActivity()并结合Zaz Gmy的回答和Dipa​​k Keshariya的回答(相同)。