我在填充类型时遇到了一些Spinner
困难List
。
目标:当Button
在主菜单上按下 a 时,它会执行任务 GetTownsTask,该任务会Spinner
在新屏幕上填充 a,但在设置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>