我是Stackoverflow的新手,也是Android的编程
我在AndroidApp中完成了这段代码:
public class MainActivity extends ActionBarActivity {
private Spinner spinner;
private LinkedList<Integer> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
this.ageSpinner();
}
private void ageSpinner(){
list = new LinkedList<Integer>();
spinner = (Spinner) this.findViewById(R.id.spinner1);
for(Integer i=0; i<=4; i++){
list.add(i);
}
ArrayAdapter<Integer> spinnerAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, list);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
}
我的logCat会给我一个NullPointerException
。
我试过这个代码,将Linkelist更改为ArrayList,String Array,但我的应用程序崩溃了。
答案 0 :(得分:1)
您需要实例化Spinner,以使其不为空。
在rootView.findViewById(R.id.spinner1)
方法中使用onCreate
可以解决问题。
答案 1 :(得分:1)
试试此代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
spinner = (Spinner)findViewById(R.id.spinner1);
ageSpinner();
ArrayAdapter<Integer> spinnerAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, list);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
}
private void ageSpinner(){
list = new ArrayList<Integer>();
for(int i=0; i<=4; i++){
list.add(i);
}