简体   繁体   English

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

[英]Passing null in putExtra in Android Intent giving compile time error?

I'm trying to use putExtra(String,String) in my code to pass null . 我正在尝试在我的代码中使用putExtra(String,String)来传递null As the parameter suggests the second parameter can be null as it is a string and I can send it 正如参数所示,第二个参数可以为null因为它是一个字符串,我可以发送它

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

When i use the above code it gives me error saying : 当我使用上面的代码时,它给我错误说:

The method putExtra(String, String) is ambiguous for the type Intent 方法putExtra(String,String)对于Intent类型是不明确的

However it allows me to use : 但它允许我使用:

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

Kindly enlighten me on this. 请在此赐教我。 Thanks in advance. 提前致谢。

When you use null , the compiler doesn't know which is the type you want to use and cannot decide which overload of the method to use. 当您使用null ,编译器不知道您要使用哪种类型,并且无法确定要使用的方法的重载。

You can cast your null to String to inform compiler which method you use: 您可以将null转换为String以通知编译器您使用哪种方法:

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

Alternatively, you can create a variable and set it to null : 或者,您可以创建一个变量并将其设置为null

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

问题是因为第二个参数为null它无法告诉您要调用哪个方法: putExtra(String name, float value)putExtra (String name, byte[] value)putExtra (String name, long[] value)等等......

This is probably because Android can not determine what you are passing ( String , boolean , int ) when you use 这可能是因为Android在您使用时无法确定您传递的内容( Stringbooleanint

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

but when you use 但是当你使用的时候

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

it knows that you are passing it as a String 它知道你将它作为String传递

Use intent.removeExtra(extraName) instead. 请改用intent.removeExtra(extraName)。 It clears the extra and is more clean than using typecasting in putExtra. 它清除了额外的内容,比在putExtra中使用类型转换更干净。

https://developer.android.com/reference/android/content/Intent.html https://developer.android.com/reference/android/content/Intent.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM