应用程序在 CreateOptionsMenu 上崩溃(可能)
App crashes onCreateOptionsMenu (maybe)
让我说,在遇到这个问题之前,我几乎搞砸了我的整个项目,有几天的错误并最终解决了它们。
我的 Android 应用程序现在几乎可以正常工作,只是每当我单击“选项”菜单(在任何 activity 中,而不仅仅是我在此处发布的这个)它会意外崩溃并显示一条奇怪的消息对我的代码进行任何引用。
这是堆栈跟踪:
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, Whosebug 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>
为什么会以这种奇怪的方式崩溃?
抱歉,问题太长了,您可以忽略我发布的第一个代码,因为我认为错误不存在(如果有的话...)。
献给正在尝试解决此错误的勇敢者。
菜单一直使应用程序崩溃:所以我决定创建一个导入所有旧文件的新项目,并将支持库更新到 v27.0.2(从 25.3.1 开始)。
处理了一个小时左右:现在,当我启动该应用程序时,它告诉我它崩溃了,但没有抛出任何错误。
当我点击 "Close application" 时,应用程序继续正常运行,菜单运行完美。
TLDR
放弃并且
git 签出 [olderVersionWithNoErrors]
让我说,在遇到这个问题之前,我几乎搞砸了我的整个项目,有几天的错误并最终解决了它们。 我的 Android 应用程序现在几乎可以正常工作,只是每当我单击“选项”菜单(在任何 activity 中,而不仅仅是我在此处发布的这个)它会意外崩溃并显示一条奇怪的消息对我的代码进行任何引用。
这是堆栈跟踪:
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, Whosebug 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>
为什么会以这种奇怪的方式崩溃? 抱歉,问题太长了,您可以忽略我发布的第一个代码,因为我认为错误不存在(如果有的话...)。
献给正在尝试解决此错误的勇敢者。
菜单一直使应用程序崩溃:所以我决定创建一个导入所有旧文件的新项目,并将支持库更新到 v27.0.2(从 25.3.1 开始)。
处理了一个小时左右:现在,当我启动该应用程序时,它告诉我它崩溃了,但没有抛出任何错误。 当我点击 "Close application" 时,应用程序继续正常运行,菜单运行完美。
TLDR 放弃并且
git 签出 [olderVersionWithNoErrors]