Wesley Peeters Wesley Peeters - 16 days ago 7
Android Question

NullPointerException on initialized object

I'm working on my first android app, and I'm trying to add a

spinner
to my view. By looking at the Android Developers Guide, I figured out how to add it to my view, and how to actually add items to the spinner.

Except for when I actually try to add items and the following pops up:

Java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference


As you can see I'm trying to run
.setAdapter()
on a spinner object. Normally this error would occur if I would try this without initializing the spinner object, but I did:

Spinner spinner = (Spinner) findViewById(R.id.where_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.where_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);


The code above is all called after I call
setContentView()
so that's not the problem.

How can it be that something as simple as a spinner is causing me so much trouble?

Thanks.

EDIT

After I saw a particular comment, I saw that I forgot to add that the layout file that contains
where_spinner
is the layout used for a dialog. The
where_spinner
should be accessible though, since any other objects in that layout also are.

Answer

Your spinner is null. Activity#findViewById() returns nulls if the view is not found in the activity's view hierarchy you've set with setContentView(), or setContentView() has not been called at all.

Based on the comments your where_spinner is in fact in a dialog view hierarchy. Call findViewById() on the dialog's hierarchy and not on the activity to find it.