应用程序崩溃onCreateOptionsMenu(也许)

问题描述 投票:0回答:1

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

这是堆栈跟踪:

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;
}
}

这是最重要的部分:

@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);
}

这是main_activity_menu.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>

这里布局activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
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"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.cats.timemanager.activities.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:tint="@color/white"
    app:srcCompat="@drawable/apps_icon" />

</android.support.design.widget.CoordinatorLayout>

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

android android-layout menu android-menu
1个回答
0
投票

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

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

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

TLDR只是放弃和

git checkout [olderVersionWithNoErrors]

© www.soinside.com 2019 - 2024. All rights reserved.