startActivityForResult 在 startActivity 工作时崩溃

startActivityForResult crashes while startActivity works

我有一个 activity 正在开始:

Intent intent = new Intent(this, CreateItemDetailsActivity.class);
if(storeId != null) {
    intent.putExtra(Identifiers.STORE_ID, storeId);
}
intent.putExtra(Identifiers.ITEM_NAME, name);
intent.putExtra(Identifiers.ITEM_DESCRIPTION, description);
startActivity(intent);

这行得通,但现在我需要 return 数据到原来的 activity,所以我将 startActivity 调用更改为:

startActivityForResult(intent, CREATE_ITEM_RESULT);

(CREATE_ITEM_RESULT只是我编的随机整数63463657)

但是,我的应用程序在没有调用任何 onCreate 方法(我已经实现并在两者中都设置了断点)的情况下崩溃了:

Uncaught exception in thread main: java.lang.IllegalStateException: Could not execute method for android:onClick
android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)

(代码在按钮单击处理程序中调用,因此 onClick

我看到 有同样的问题,但接受的答案建议删除一行,recipe.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);,我没有。

为什么我在 startActivityForResult 上崩溃,而 startActivity 运行正常?

(我的最低SDK级别是16,目标和编译SDK级别是27,我是运行 Android 8.1模拟器)

如果没有看到关于此问题的任何文档,但尝试使用四位数 int 值应该可以消除错误。

我已经阅读了 Google startActivityForResult 的文档,但我没有找到任何关于最大 int 大小的参考。甚至代码文档也指出:

@param requestCode If >= 0, this code will be returned in the onActivityResult() when the activity exists

所以,没有提到最大 int 值。奇...


编辑

感谢@MidasLefko 找到此信息:

RequestCodes can only be a max of 0xffff (65535). So you are probably calling startActivityForResult(intent, REQUEST_CODE); and REQUEST_CODE is greater than 65535.

在此网站上:

https://code-examples.net/en/q/db5947

在非支持Activity class implementation of startActivityForResult there is no restriction on the maximum int for requestCode, as long as it is positive. However FragmentActivity (and by extension AppCompatActivity) overrides this behavior(文档):

void startActivityForResult (Intent intent, int requestCode)

Modifies the standard behavior to allow results to be delivered to fragments. This imposes a restriction that requestCode be <= 0xffff.

source code of FragmentActivity 中发现以下有用的评论:

A hint for the next candidate request index. Request indicies are ints between 0 and 2^16-1 which are encoded into the upper 16 bits of the requestCode for Fragment.startActivityForResult(...) calls. This allows us to dispatch onActivityResult(...) to the appropriate Fragment. Request indicies are allocated by allocateRequestIndex(...).

java中的int是32位的,FragmentActivity使用16位来决定将结果发送到哪个fragment,另外16位供开发者使用。