Wesley Peeters Wesley Peeters - 10 months ago 66
Android Question

NullPointerException on initialized object

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

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
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);

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

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



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

Answer Source

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.