在Android Intent中的putExtra方法中传递null会导致编译时错误?

8

我正在尝试在我的代码中使用putExtra(String,String)来传递null。 正如该参数所示,第二个参数可以是null,因为它是一个字符串,我可以发送它。

this.getIntent().putExtra(AppConstant.TestString, null);

当我使用上述代码时,它会给我一个错误提示: Intent 的 putExtra(String, String) 方法对于类型 Intent 来说是有歧义的。 然而,它允许我使用:
this.getIntent().putExtra(AppConstant.TestString, "");

请帮我解释一下这个问题,提前感谢。

4个回答

19

当您使用null时,编译器不知道您想要使用哪种类型,并且无法决定使用哪个方法的重载。

您可以将null强制转换为String,以通知编译器您要使用哪个方法:

this.getIntent().putExtra(AppConstant.TestString, (String)null);

或者,您可以创建一个变量并将其设置为null

String param = null;
this.getIntent().putExtra(AppConstant.TestString, param);

1
问题在于第二个参数为null时,它无法确定您要调用哪个方法:putExtra(String name, float value)putExtra(String name, byte[] value)putExtra(String name, long[] value)等。

0

0

这可能是因为当您使用

this.getIntent().putExtra(AppConstant.TestString, null);

时,Android无法确定您正在传递什么(Stringbooleanint),但是当您使用

this.getIntent().putExtra(AppConstant.TestString, "");

时,它知道您正在将其作为String传递。


我知道现在说有点晚了,但在Java中,boolean默认为false,而int默认为0,而不是null。对吗? - CodeWarrior
是的,但当您使用 null 时,它是不明确的。 - Apoorv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接