我在使用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