0

I just wanted to add the spinner in the action bar but after a lot of debugging I failed to understand why the getActionView() method is not returning any view(I tested with a view also).Logcat is showing:

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

This is my Java Code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);


        MenuItem item=menu.findItem(R.id.spinner_item);
        Spinner spinner=(Spinner)item.getActionView();
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.items,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);


        return true;
    }

and this is my res/menu/menu.xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.haha.Main" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/spinner_item"
        android:title="@string/sort"
        app:showAsAction="always"
        android:actionLayout="@layout/spinner_main"
        android:checkable="true"
        />

</menu>

And this is layout/spinner_main.xml file

<?xml version="1.0" encoding="UTF-8"?>
<Spinner 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/items" 
    android:background="#212121"
    />
Aakash
  • 5,181
  • 5
  • 20
  • 37
Nitish Chopra
  • 273
  • 1
  • 4
  • 11

0 Answers0