0

我需要在我的应用程序中显示一个对话框。在此对话框中有一个 Spinner。所以我使用这段代码来显示对话框并填充 Spinner:

public class setup4 extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setup4);
}

//On bottone setup 4
public void onSetup4bottone(View v)
{
    AlertDialog.Builder customDialog = new AlertDialog.Builder(this);
    customDialog.setTitle("Aggiungi ora scolastica");
    LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view=layoutInflater.inflate(R.layout.aggiungi_ora,null);
    customDialog.setView(view);

    List<String> materie = new ArrayList<String>();
    materie.add("ADASDASD"); materie.add("LOLOLOL");

    Spinner spinner = (Spinner) findViewById(R.id.aggiungi_ora_materia);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, materie);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    customDialog.show();
}
}

onSetup4bottone 是必须调用对话框的简单按钮的单击事件。我不明白为什么我在这行代码中得到 java.lang.NullPointerException:

spinner.setAdapter(adapter);

感谢帮助 :)

4

1 回答 1

2

那么显而易见的候选人是spinner空的,这表明:

Spinner spinner = (Spinner) findViewById(R.id.aggiungi_ora_materia);

正在返回 null。首先要做的是检查 - 记录是否spinner为空。

您确定您使用的是正确的 ID 吗?根据文档findViewById如果您使用错误的 ID,将返回 null:

从在 onCreate(Bundle) 中处理的 XML 中查找由 id 属性标识的视图。

如果找到则返回
视图,否则返回 null。

于 2012-08-05T17:56:37.400 回答