Fix one bug in Android 官方提供的例子

在android 官方提供的 Notepad tutorial的 Notepadv2Solution这个例子中,我发现有一个bug。

 

当运行后,新创建一个item,当我们不点击confirm按钮,而是选择取消按钮,或者 esc键的时候,就会报应用程序崩溃的错误。

 

结合android的生命周期原理,我发现是这个代码中存在一个问题。

 

在代码中,其覆盖了 onActivityResult(int requestCode, int resultCode, Intent intent)这个Activity基类中的函数。

 

这是 api文档中关于这个函数的介绍。

 

 

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

You will receive this call immediately before onResume() when your activity is re-starting.

Parameters
requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
resultCode The integer result code returned by the child activity through its setResult().
data

An Intent, which can return result data to the caller (various data can be attached to Intent "extras")。

 

 

 

 

 

 

 

在这个官方提供的代码中,其覆盖了基类中这个函数,但是其中并没有处理取消,或者esc键,当取消的时候,进入到这个函数中,会有一个空指针错误,导致程序崩溃

 

 

 

进入这个函数后,intent将为null,在调用他的成员函数时就会出错。

 

修改这个bug很容易,因为当按取消键,或者esc按钮的时候,其resultcode是RESULT_CANCELED,我们只要加一个判断即可。

 

修改后的代码如下,

 

 

经测试后,运行良好。

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值