将Activity更改为AppCompatActivity时出现NullPointerException

时间:2016-11-29 20:35:39

标签: android nullpointerexception android-support-library oncreateoptionsmenu

我将我的课程从Activity更改为AppCompatActivity。

并将item.getActionView()更改为MenuItemCompat.getActionView(item)

现在我在下面的代码中获得NPE。

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

如何解决错误?

1 个答案:

答案 0 :(得分:4)

使用app:actionViewClass时,您必须使用android:actionViewClass,而不是AppCompatActivity