2012-08-05 102 views
0

我需要在我的应用程序中显示一个对话框。在这个对话框中有一个微调。所以我用这个代码显示对话框,并填补了微调:Android AlertDialog给出错误java.lang.NullPointerException

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

感谢您的帮助:)

回答

2

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

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

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

您确定您使用的是正确的ID吗?按照the docs,如果你使用了错误的ID findViewById将返回null:

Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

Returns
The view if found or null otherwise.

+1

是我'肯定这是aggiungi_ora.xml的微调代码(对话XML文件) '<微调机器人:ID = “@ + id/aggiungi_ora_materia”android:layout_width =“match_parent”android:layout_height =“wrap_content”/>' – barbo 2012-08-05 18:44:47

+1

@barbo:我认为Jon在这里是正确的。因为您试图从活动的内容视图中夸大它,所以微调器可能为'null'。然而,你可能的意思是:'Spinner spinner =(Spinner)view.findViewById(R.id.aggiungi_ora_materia);''''注意在自定义对话框'view'上如何调用'findViewById(...)',并且而不是活动。换句话说:你试图从错误的布局中夸大微调。 – 2012-08-05 19:18:22

+0

我知道问题在于微调框为空,因为它没有在xml中找到微调框,但是我能做什么? – barbo 2012-08-05 19:37:25

相关问题