0

I'm trying to set my spinner position on activity entry but i get this msg on logcat

Attempt to invoke virtual method 'void android.widget.Spinner.setSelection(int)' on a null object reference

I have and array delcared as:

<string-array name="genres">
    <item>Action</item>
    <item>Animation</item> 
</string-array>

in the activity i have

    movieGenre = (Spinner) findViewById(R.id.dd_genre);
    Log.e("ListView set Item", String.valueOf(movieItem.getaNGenre()));
    movieGenre.setSelection(movieItem.getaNGenre());

logcat shows me the number correctly:

05-09 12:46:35.624    4940-4940/simpleapps.movierandomizer E/ListView set Item﹕ 3

but when i set the position, it wont accept the number. I dont understand why it says "on a null object reference" when i have declared it.

Richard
  • 6,812
  • 5
  • 45
  • 60
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Vucko May 09 '16 at 13:40

2 Answers2

0

Did you populate the spinner with the items (probably the string array in this case?) Also, if the item number (3 in this case) that you are trying to set,is more than the spinner items, it will throw a run time error.

user1930106
  • 779
  • 1
  • 6
  • 19
0

You have to set the adapter for the spinner first. After setting up the adapter it won't throw the exception that you have mentioned.

Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.planets_array, android.R.layout.simple_spinner_item);

// Specify the layout to use when the list of choices appears
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
user492888
  • 207
  • 3
  • 17