android中setAdapter步骤期间ArrayAdapter的NullPointerException

时间:2012-03-28 13:20:46

标签: java android nullpointerexception

  

可能重复:
  NullPointerException for ArrayAdapter in android

这是我的代码

String[] city_array = response_city.toString().split(",");  
Log.d("city array", city_array[0]);  
ArrayAdapter<String> cityArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);  
Log.d("city array adapter","count1 = " + cityArrayAdapter.getCount());  
cityArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
int length = city_array.length;  
for (int i = 0; i < length; i++)
    cityArrayAdapter.add(city_array[i]);  
Log.d("city array adapter","count2 = " + cityArrayAdapter.getCount());  
city_spinner.setAdapter(cityArrayAdapter);  

第一步中的response_city是来自网络服务器的回复,其中包含“pune,mumbai,bangalore”

3 个答案:

答案 0 :(得分:1)

我没有看到city_spinner初始化的位置。记录city_spinner,如果为null,则表明您已发现问题。空指针异常通常意味着某些东西没有被初始化,并且它似乎很可能是罪魁祸首。

答案 1 :(得分:0)

像这样改变

String[] city_array = response_city.toString().split(",");  
Log.d("city array", city_array[0]);  
ArrayLlist<String> items = new ArrayList<String>();

int length = city_array.length;  
for (int i = 0; i < length; i++)
items.add(city_array[i]);

ArrayAdapter<String> cityArrayAdapter = new ArrayAdapter<String>(this,    
android.R.layout.simple_dropdown_item_1line, items);  
Log.d("city array adapter","count1 = " + cityArrayAdapter.getCount());  
cityArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  

Log.d("city array adapter","count2 = " + cityArrayAdapter.getCount());  
city_spinner.setAdapter(cityArrayAdapter);   

答案 2 :(得分:0)

city_spinner检查是否正确分配了XML视图....