Java 按下后退按钮时,Android 应用程序崩溃

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21094347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:31:46  来源:igfitidea点击:

Android app crashes when back button is pressed

javaandroidcrash

提问by Matthias

I have run into an annoying crash in my app when the user clicks the back button.

当用户单击后退按钮时,我的应用程序遇到了令人讨厌的崩溃。

In my app, i have 3 relevant activities:

在我的应用程序中,我有 3 个相关的活动:

  • MainActivity: shows a list of Persons
  • PersonActivity: shows a list of all the Payments of a Person
  • AddPaymentActivity: has input elements to add a Payment to a Person
  • MainActivity:显示人员列表
  • PersonActivity:显示一个人的所有付款的列表
  • AddPaymentActivity:具有向人员添加付款的输入元素

From MainActivity the user can either tap on a Person's name in the list to go to PersonActivity or use a "+" button next to the Person's name and jump directly into AddPaymentActivity. In PersonActivity there is a "+" button that leads to AddPaymentActivity, too.

在 MainActivity 中,用户可以点击列表中的人员姓名以转到人员活动,也可以使用人员姓名旁边的“+”按钮直接跳转到 AddPaymentActivity。在 PersonActivity 中,也有一个“+”按钮可以指向 AddPaymentActivity。

The Perons data is stored in a Java Person class that implements the Serializable interface. When starting an Activty i forward the Person Object via

Perons 数据存储在实现 Serializable 接口的 Java Person 类中。启动活动时,我通过以下方式转发人员对象

intent.putExtra(MainActivity.PERSON_MESSAGE, person);

When i go from MainActivity directly into AddPaymentActivity (via "+"), the back button works fine. If i however use start AddPaymentActivity from PersonActivity, my application crashes with a null pointer exception.

当我从 MainActivity 直接进入 AddPaymentActivity(通过“+”)时,后退按钮工作正常。但是,如果我从 PersonActivity 使用 start AddPaymentActivity,我的应用程序会因空指针异常而崩溃。

Using the debugger i noticed that PersonActivity.onCreate() is called (again?) when the back button is pressed. Why does this happen when going back form AddPaymentActivity to PersonActivity? And why does that NOT happen when going back from AddPaymentActivity to MainActivity? What can i do to fix the problem?

使用调试器,我注意到当按下后退按钮时 PersonActivity.onCreate() 被调用(再次?)。为什么在从 AddPaymentActivity 返回到 PersonActivity 时会发生这种情况?为什么从 AddPaymentActivity 返回到 MainActivity 时不会发生这种情况?我能做些什么来解决这个问题?

Stack trace:

堆栈跟踪:

01-13 10:11:01.423: E/AndroidRuntime(1022): FATAL EXCEPTION: main
01-13 10:11:01.423: E/AndroidRuntime(1022): Process: de.emteg.cashsplit, PID: 1022
01-13 10:11:01.423: E/AndroidRuntime(1022): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.emteg.cashsplit/de.emteg.cashsplit.PersonActivity}: java.lang.NullPointerException
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.ActivityThread.access0(ActivityThread.java:135)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.os.Looper.loop(Looper.java:137)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.ActivityThread.main(ActivityThread.java:4998)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at java.lang.reflect.Method.invoke(Method.java:515)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at dalvik.system.NativeStart.main(Native Method)
01-13 10:11:01.423: E/AndroidRuntime(1022): Caused by: java.lang.NullPointerException
01-13 10:11:01.423: E/AndroidRuntime(1022):     at java.math.BigDecimal.<init>(BigDecimal.java:425)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at de.emteg.cashsplit.PersonActivity.onCreate(PersonActivity.java:37)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.Activity.performCreate(Activity.java:5243)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-13 10:11:01.423: E/AndroidRuntime(1022):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
01-13 10:11:01.423: E/AndroidRuntime(1022):     ... 11 more

MainActivity.onCreate:

MainActivity.onCreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_overview);

    persons = new ArrayList<Person>();

            // Populate list with some test person objects
    Person p = new Person("Frank");
    p.getPayments().add(new Payment("test1", new BigDecimal(5.7)));
    persons.add(p);

    p = new Person("Peter");
    persons.add(p);

    ListView list = (ListView) findViewById(R.id.listView1);
    PersonAdapter adapter = new PersonAdapter();
    list.setAdapter(adapter);
    // output....
}

PersonActivity.onCreate():

PersonActivity.onCreate():

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_person);

    Intent intent = getIntent();        
    this.person = (Person) intent.getSerializableExtra(MainActivity.PERSON_MESSAGE);
    this.share = new BigDecimal(intent.getStringExtra(MainActivity.SHARE_MESSAGE));
    this.totalSum = new BigDecimal(intent.getStringExtra(MainActivity.SUM_MESSAGE));
    this.diff = person.getSum().subtract(share);

    setupActionBar();

    // output...
}

AddPaymentActivty.onCreate():

AddPaymentActivty.onCreate():

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_payment);
    // Show the Up button in the action bar.
    setupActionBar();

    Intent intent = getIntent();

    this.person = (Person) intent.getSerializableExtra(MainActivity.PERSON_MESSAGE);

    if (intent.hasExtra(MainActivity.PAYMENT_MESSAGE)) {
        this.payment = (Payment) intent.getSerializableExtra(MainActivity.PAYMENT_MESSAGE);
        // output....
    } else {
        this.payment = null;
        // output...
    }

}

回答by user3091819

It must be because of a null pointer exception which causes your app to crash.

这一定是因为空指针异常导致您的应用程序崩溃。

First, check if in your PersonActivity needs a value that is not passed/set when back button is pressed from your AddPaymentActivity.

首先,检查您的 PersonActivity 中是否需要在从 AddPaymentActivity 按下后退按钮时未传递/设置的值。

You may also override the onResume() function, it will be called when back button is pressed.

您也可以覆盖 onResume() 函数,它会在按下后退按钮时调用。

回答by Andros

Your problem is in one of those 2 lines :

您的问题出在以下两行之一中:

this.share = new BigDecimal(intent.getStringExtra(OverviewActivity.SHARE_MESSAGE));
this.totalSum = new BigDecimal(intent.getStringExtra(OverviewActivity.SUM_MESSAGE));

It seems that one of your 2 getStringExtrareturn null.

看来你的 2 之一getStringExtra返回 null。

回答by RileyManda

Check that you have not added finish(); after your intent.The intent/activity you wish to return to from the previous activity,when adding this intent to the parent activity,make sure that the parent activity invoking this intent does not have finish();.for example:

检查您是否没有添加finish(); 在您的意图之后。您希望从前一个活动返回的意图/活动,将此意图添加到父活动时,请确保调用此意图的父活动没有完成();例如:

Main Activity calling payment activity:

调用支付活动的主要活动:

Intent d = new Intent(getApplicationContext(),
                PaymentActivity.class);
        startActivity(d);
        finish();***//remove this***
        return true;

if you tell the activity calling another activity to finish(),this basically means that activity called can neevr return to the previous activity, therefore this below is correct: //finish();has been removed

如果你告诉活动调用另一个活动完成(),这基本上意味着被调用的活动不能返回到前一个活动,因此下面是正确的: //finish();已被删除

 Intent d = new Intent(getApplicationContext(),
                PaymentActivity.class);
        startActivity(d);
        return true;

The next thing you need to do is make sure your manifest has parent activity added to the activities.

您需要做的下一件事是确保您的清单已将父活动添加到活动中。

Eg:

例如:

<activity
        android:name=".PaymentActivity"
        android:label="@string/paymentlabel"
        android:parentActivityName=".PaymentActivity" />

And in your Payment Activity onCreate add,the following:

并在您的付款活动 onCreate 添加,以下内容:

assert getSupportActionBar() != null;***> //this tells the application that ActionBar is not null and therefore dont call an java null exceptions and crash the activity


    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);