错误信息:Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.SpinnerTest.MyActivity.getdata(MyActivity.java:55)
at com.example.SpinnerTest.MyActivity.onCreate(MyActivity.java:36)
package com.example.SpinnerTest;
import android.app.Activity;
import android.os.Bundle;
import android.text.AndroidCharacter;
import android.view.View;
import android.widget.*;
import java.util.*;
public class MyActivity extends Activity implements AdapterView.OnItemSelectedListener {
/**
* Called when the activity is first created.
*/
private TextView T1;
private Spinner S1;
//private List<String> L1;
private String[] L1 = {"北京", "上海", "成都", "广州"};
//private ArrayAdapter<String> A1;
private SimpleAdapter s2;
private List<Map<String,Object>> list;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
T1 = (TextView) findViewById(R.id.TextView);
S1 = (Spinner) findViewById(R.id.spinner);
//1.设置数据源
//L1 = new ArrayList<String>();
// L1.add("北京");L1.add("上海");L1.add("成都");L1.add("广州");
//2.设置一个适配器
// A1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,L1);
s2 = new SimpleAdapter(this, getdata(), R.layout.item, new String[]{"pic", "text"}, new int[]{R.id.imageView, R.id.textView});
list = new ArrayList<Map<String, Object>>();
//3.适配器设置一个下拉列表样式
s2.setDropDownViewResource(R.layout.item);
//4.Spinner加载适配器
S1.setAdapter(s2);
//5.Spinner设置监听器
S1.setOnItemSelectedListener(this);
}
private List<Map<String,Object>> getdata()
{
for (int i = 0;i < L1.length;i++)
{
Map<String,Object> map = new HashMap<String,Object>();
map.put("pic",R.drawable.ic_launcher);
map.put("text","陶融" + i);
list.add(map);
}
return list;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String cityname = (String)s2.getItem(position);
T1.setText("您选择的城市是:" + cityname);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}