java - onActivityResult wont work after onBackPressed
问题描述
I created an app with 2 screens: Activity A (main) and Activity B.
When the user clicks on the search button in activity A it opens a ListView named Activity B.
In this ListView the user has CheckBoxes that he clicks and once he clicks Done, the results are returned to Activity A by using onActivityResult.
For some reason, if let say I do the following:
1) clicked the search button in activity A. 2) chose 1 item in Activity B but didn't click done. Instead, I clicked the return button. 3) re-enter again to activity B 4) choose items + click done
Then my app crashes because it says the result is null.
It seems like after I'm clicking on the return button, that the onActivity result is not working between activity A and B.
My code is:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == ChatActivity.RESULT_OK){
new CountDownTimer(1000, 500) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
confirmedBooks = (ArrayList<DiscoverBooks>)data.getSerializableExtra("confirmedItems");
DateInMillis = data.getLongExtra( "dateInMillis", System.currentTimeMillis());
}
}.start();
}
if (resultCode == ChatActivity.RESULT_CANCELED) {
}
}
}
and:
Btn_Done.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent confirmedData = new Intent();
confirmedData.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
confirmedData.putExtra( "confirmedItems", (Serializable) itemsSelected );
confirmedData.putExtra( "dateInMillis",DateInMillis );
setResult(ChatActivity.RESULT_OK,confirmedData);
finish();
}
} );
NOTE:
I added the line confirmedData.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
because I was hoping that it will clear the data from the previous choose however it also seems to work not so well.
If I do these actions without clicking on the return button everything works correctly.
Any reason for this?
Thank you!
解决方案
请检查您是否使用活动 A调用了活动 BstartActivityforResult
而且您不需要在设置结果上设置标志。您需要像这样更新它:
Btn_Done.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent confirmedData = new Intent();
confirmedData.putExtra( "confirmedItems", (Serializable) itemsSelected );
confirmedData.putExtra( "dateInMillis",DateInMillis );
setResult(ChatActivity.RESULT_OK,confirmedData);
finish();
}
} );
推荐阅读
- c# - .Net 自定义配置部分未加载
- gcc - 使用弱声明覆盖 c 代码中的 GCC 链接器符号
- java - Apache PDFBox - 无法读取 PDF 中的所有 Web 链接
- php - Wordpress:如何以编程方式每天添加帖子?
- javascript - 谷歌网站网站语言翻译
- vb.net - 使用 TableAdapter 配置向导时出错,SqlServer.Types v15
- c# - 如果匹配记录不可用,则获取任何单个记录 - Linq
- java - 在 Java 中映射列表
- java - 基本的 java net 客户端返回 400
- javascript - 使用 `!=` 和 `==` 比较 Object 和 Boolean 有不同的结果