选项菜单无法正常工作

时间:2017-12-01 12:08:45

标签: android nullpointerexception android-optionsmenu

我在Android工作室工作,一切正常,但突然出现问题。当我单击右上方的选项菜单按钮时,菜单不会膨胀并且应用程序崩溃,菜单项在设置为app:showAsAction="always"时工作正常但在app:showAsAction="never"时崩溃。此外,当我重建我之前的项目来检查问题时,他们也遇到了这个问题,而这个问题以前就不存在了。

MainActivity.java

public class MainActivity extends AppCompatActivity {

Toolbar toolbare;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_activity);

        toolbare = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbare);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list_view_type, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.i("info", "In optionsItemSelected");
       switch (item.getItemId()) {
           case R.id.view_type_single:
               NoteFragSingle noteSingle = new NoteFragSingle();
               FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
               fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                       android.R.anim.fade_out);
               fragmentTransaction.replace(R.id.fragMent, noteSingle);
               fragmentTransaction.commitAllowingStateLoss();
               return true;
           case R.id.view_type_multi:
               NoteFragGrid noteFragGrid = new NoteFragGrid();
               fragmentTransaction = getSupportFragmentManager().beginTransaction();
               fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                       android.R.anim.fade_out);
               fragmentTransaction.replace(R.id.fragMent, noteFragGrid);
               fragmentTransaction.commitAllowingStateLoss();
               return true;

               default:
                   return super.onOptionsItemSelected(item);
       }

    }

menu_list_view_type.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/view_type_multi"
        android:icon="@drawable/ic_view_module_black_24dp"
        android:title="Multi Column View"
        app:showAsAction="never" />
    <item
        android:id="@+id/view_type_single"
        android:icon="@drawable/ic_view_list_black_24dp"
        android:title="Single Column View"
        app:showAsAction="never" />
</menu>

应用级 build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

错误每次出现在当前以及之前正常工作的每个项目中。

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.support.v7.view.menu.ListMenuItemView.setTitle(ListMenuItemView.java:127)
at android.support.v7.view.menu.ListMenuItemView.initialize(ListMenuItemView.java:113)
at android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:100)
at android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
at android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
at android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
at android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
at android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
at android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:803)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

我试过干净并重建,无效并重新启动但没有任何效果请帮助我。
修改
这是片段代码

public class NoteFragSingle extends Fragment {
    private NoteAdapter mAdapter;
    RecyclerView rView;
    SQLiteDatabase db;
    Cursor cursor;
    RecyclerView.LayoutManager mLayoutManager;
    private List<Note> noteList = new ArrayList<Note>();


    public NoteFragSingle() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_note_frag_single, container, false);
        rView = (RecyclerView) v.findViewById(R.id.recycler_view);
        TextView empty = (TextView) v.findViewById(R.id.empty_single);
        mAdapter = new NoteAdapter(getActivity(), noteList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        rView.setLayoutManager(mLayoutManager);
        rView.setItemAnimator(new DefaultItemAnimator());
        rView.setAdapter(mAdapter);
      /*  if(noteList.isEmpty()){
            rView.setVisibility(View.GONE);
            empty.setVisibility(View.VISIBLE);
        }
        else {
            rView.setVisibility(View.VISIBLE);
            empty.setVisibility(View.GONE);
        }
        */

        try {
            Databasehelper textoDatabaseHelper = new Databasehelper(getActivity());
            db = textoDatabaseHelper.getReadableDatabase();
            cursor = db.query("NOTES", new String[]{"_id","TITLE", "DESCRIPTION", "DATE"}, null, null, null, null, null);
            if (cursor.moveToFirst()){
                do {
                    String Title = cursor.getString(1);
                    String Description = cursor.getString(2);
                    String Date = cursor.getString(3);
                    Note note = new Note(Title, Description, Date);
                    noteList.add(note);
                    mAdapter.notifyDataSetChanged();
                }while(cursor.moveToNext());

            }
        } catch (SQLiteException e) {
            Toast.makeText(getActivity(),"Cannot retrieve notes. Try again", Toast.LENGTH_SHORT).show();
        }


        return  v;
    }



}

1 个答案:

答案 0 :(得分:0)

你在错误的点上称通货膨胀。您应该在致电 super()之前执行此操作。如下所示。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu
    getMenuInflater().inflate(R.menu.menu_list_view_type, menu);
    return super.onCreateOptionsMenu(menu);;
}