应用程序崩溃onCreateOptionsMenu(也许)

时间:2017-12-28 21:35:59

标签: android android-layout menu android-menu

让我说在面对这个问题之前,我几乎搞砸了我的整个项目,有几天的bug,最终解决了它们。 我的Android应用程序现在几乎没有问题,只要我点击选项菜单(在任何活动中,而不仅仅是我在这里发布的那个),它会意外地崩溃,并发出一条奇怪的消息,该消息不会引用任何内容。我的代码。

这是堆栈跟踪:

singleRound(computerPlay(), getPlayerSelection());

看起来我的应用程序没有任何理由崩溃。 这是我的代码:

12-28 22:15:07.842 11672-11672/com.cats.timemanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.cats.timemanager, PID: 11672
                                                                  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:789)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

这是其中最重要的部分:

package com.cats.timemanager.activities;
//Cannot write imports here sorry, StackOverflow editor sucks

public class MainActivity extends AppCompatActivity {
/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

AppSettingsData myAppSettingsData;

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

    myAppSettingsData = new AppSettingsData(getApplicationContext());
    if (myAppSettingsData.getBoolean("first_start", true)) {
        Intent tempIntent = new Intent(getBaseContext(), IntroActivity.class);
        startActivity(tempIntent);
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    mViewPager = (ViewPager) findViewById(R.id.container);

    setSupportActionBar(toolbar);
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            setTitle(mSectionsPagerAdapter.getPageTitle(position));
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    setTitle(mSectionsPagerAdapter.getPageTitle(0));


    /**
     * TODO find out sth else to check whether the service is on
     */
    if (isServiceRunning(ScreenService.class) == false) {
        Intent intentScreenService = new Intent(getApplicationContext(), ScreenService.class);
        intentScreenService.putExtra("EVENT", 1);
        getApplicationContext().startService(intentScreenService);
    }


    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent myIntent = new Intent(getBaseContext(), ApplicationStatisticsActivity.class);
            startActivity(myIntent);
        }
    });
}


@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_activity_menu, menu);
    Log.i("CATs", "THIS LOG APPEARS-> THE APP IS WORKING FINE TILL NOW.");
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.main_activity_action_settings) {
        Intent myIntent = new Intent(getBaseContext(), SettingsActivity.class);
        startActivity(myIntent);
        return true;
    }
    if (id == R.id.main_activity_action_per_app_statistics) {
        Intent myIntent = new Intent(getBaseContext(), ApplicationStatisticsActivity.class);
        startActivity(myIntent);
        return true;
    }
    if (id == R.id.main_activity_action_timeline) {
        Intent myIntent = new Intent(getBaseContext(), TimeLineActivity.class);
        startActivity(myIntent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a ApplicationStatisticsFragment (defined as a static inner class below).
        switch (position+1) {
            case 1:
                return DailyFragment.newInstance(position + 1);
            case 2:
                return WeeklyFragment.newInstance(position + 1);
            case 3:
                return MonthlyFragment.newInstance(position + 1);
            case 4:
                return YearlyFragment.newInstance(position + 1);
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show 4 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position+1) {
            case 1:
                return "Usage stats - Today";
            case 2:
                return "Usage stats - This Week";
            case 3:
                return "Usage stats - This Month";
            case 4:
                return "Usage stats - This Year";
        }
        return null;
    }
}

private boolean isServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
}

这里是main_activity_menu.xml:

@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_activity_menu, menu);
    Log.i("CATs", "THIS LOG APPEARS-> THE APP IS WORKING FINE TILL NOW.");
    //THE APP IS WORKING FINE TILL HERE. PROBABLY onCreateOptionsMenu is NOT THE PROBLEM.
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.main_activity_action_settings) {
        Intent myIntent = new Intent(getBaseContext(), SettingsActivity.class);
        startActivity(myIntent);
        return true;
    }
    if (id == R.id.main_activity_action_per_app_statistics) {
        Intent myIntent = new Intent(getBaseContext(), ApplicationStatisticsActivity.class);
        startActivity(myIntent);
        return true;
    }
    if (id == R.id.main_activity_action_timeline) {
        Intent myIntent = new Intent(getBaseContext(), TimeLineActivity.class);
        startActivity(myIntent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

这里布局为activity_main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.cats.timemanager.activities.MainActivity">
<item
    android:id="@+id/main_activity_action_per_app_statistics"
    android:orderInCategory="100"
    android:title="@string/main_activity_action_per_app_statistics" />
<item
    android:id="@+id/main_activity_action_timeline"
    android:orderInCategory="101"
    android:title="@string/main_activity_action_timeline" />
<item
    android:id="@+id/main_activity_action_settings"
    android:orderInCategory="102"
    android:title="@string/main_activity_action_settings" />
</menu>

为什么会以那种奇怪的方式崩溃? 对不起,问题是这么久,你可以忽略我发布的第一个代码,因为我不认为错误存在(如果有的话......)。

1 个答案:

答案 0 :(得分:0)

对于那些试图解决这个错误的勇敢的灵魂。

菜单一直使应用程序崩溃:所以我决定创建一个导入所有旧文件的新项目,并将支持库更新到v27.0.2(从25.3.1开始)。

工作了一个小时左右:现在,当我启动应用程序时,它告诉我崩溃没有丢失任何错误。 当我点击“关闭应用程序”时,应用程序保持正常工作,菜单工作正常。

TLDR 放弃并

git checkout [olderVersionWithNoErrors]