androidnullpointerexceptionandroid-support-libraryoncreateoptionsmenu

NullPointerException when change Activity to AppCompatActivity


I changed my class from the Activity to AppCompatActivity.

And changed item.getActionView() to MenuItemCompat.getActionView(item)

Now I get NPE in the following code.

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.messages, menu);

    MenuItem item = menu.findItem(R.id.menuTxtSize);
    Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    int index = sp.getInt(getString(R.string.pr_text_size),
            Integer.parseInt(getString(R.string.pr_default_text_size)));
    spinner.setSelection(index);


E/ACRA: ACRA caught a NullPointerException for com.alex.documentation java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setSelection(int)' on a null object reference at com.alex.message.activities.MessagesActivity

How to fix the error?


Solution

  • You have to use app:actionViewClass, not android:actionViewClass when using AppCompatActivity.