我在使用List
类型填充Spinner
时遇到一些问题。从列表中填充微调器
目的:当Button
按下主菜单上,它执行其填充新的屏幕上一个Spinner
任务GetTownsTask,但设置Adapter
时,它打破。
MainActivity.java
private class GetTownsTask extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(Void... p) {
// api calls
List<String> towns = new ArrayList<String>();
// populate towns
return towns;
}
@Override
protected void onPostExecute(List<String> townList) {
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
townList.toArray(new String[0]));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter); // line 124, breaks here
}
}
崩溃日志
FATAL EXCEPTION: main,
java.lang.NullPointerException,
at com.project.MainActivity$TestTask.onPostExecute(MainActivity.java:124)
微调屏幕
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#787878">
<Spinner
android:id="@+id/spinner"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/townTextView"
android:layout_below="@+id/townTextView"
android:layout_marginTop="10dp" />
</RelativeLayout>
返回值是'spinner'是'null'。你把它添加到你的'XML'文件中? – 2012-07-23 15:48:17
'spinner'为null,很难说出为什么没有任何额外的代码。 – dmon 2012-07-23 15:48:27
您的城镇位于顶部,但您打电话给townList.toArray()。您是否通过在onPostExecute方法中进行调试来检查townList是否为空? – kosa 2012-07-23 15:48:29