Reputation: 189
I want to create a spinner to show the list m
. But the following code gives NullPointerException
at spinner.setAdapter(spinner_adapter)
. Why does this happen?
public class Request extends ListActivity {
private static final String[] m={"A","B","O","AB","others"};
private TextView view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleAdapter adapter = new SimpleAdapter(this, getData(),
R.layout.listitem, new String[] { "name", "quant" },
new int[] {R.id.name, R.id.quant });
setListAdapter(adapter);
view = (TextView) findViewById(R.id.spinnerText);
Spinner spinner = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);
spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinner_adapter);
spinner.setOnItemSelectedListener(new SpinnerSelectedListener());
spinner.setVisibility(View.VISIBLE);
}
class SpinnerSelectedListener implements OnItemSelectedListener{
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
view.setText(""+m[arg2]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
}
Upvotes: 0
Views: 7420
Reputation: 602
Since you use ListView
Default layout both TextView
and Spinner
will be null cause there are no R.id.spinnerText
nor R.id.spinner01
So you should implement your custom layout
setContentView(...);
in this layout there should be
ListView
with an id of @android:id/list
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Spinner
with an id of @+id/spinner01
<Spinner
android:id="@+id/spinner01"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
TextView
with an id of @+id/spinnerText
<TextView
android:id="@+id/spinnerText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Upvotes: 0
Reputation: 1946
You are accessing those views in your onCreate i.e
Spinner spinner = (Spinner) findViewById(R.id.spinner01);
The id is present in R.java file, cause you have proper layout , But for accessing those will fails causing nullpointer at runtime to all of your views
You Need to add
setContentView(R.layout.main);
inside onCreate where main is your layout i.e main.xml which contains spinner01
Upvotes: 0
Reputation: 19220
Your line
Spinner spinner = (Spinner) findViewById(R.id.spinner01);
ends up the spinner
being null, since no content view has been assigned to your activity.
Thus, when trying to interact with your spinner, a NPE is thrown.
Add the setContentView(R.layout.your_layout_content);
to the onCreate method, before initializing its views.
Upvotes: 4
Reputation: 9996
Perhaps, you are trying to use IDs
from layout and you missed to call setContentView
. Call it just below super.onCreate(savedInstanceState);
setContentView(<YourLayout>);
Upvotes: 0