[英]Application is crashing with null pointer exception if i pass null value to method
Calling this method and passing null in 2nd parameter is crashing. 调用此方法并在第二个参数中传递null将导致崩溃。
App.revertMessage(actContext, null, name);
public static void revertMessage(final Context ctx, final Item item,
final String name) {
logite("revertMessage()", "item " + item == null ? "" : item.code // it is crashing here with null pointer exception
+ " name : " + name == null ? "" : item.name );
}
public static void logite(String tag, String msg) {
tag = "sTrack " + tag;
Log.e(tag, msg);
}
Item class is 项目类别为
public class Item {
public String code, name, packName;
public Item(HashMap<String, String> data) {
code = data.get(XT.ITEM_CODE);
name = data.get(XT.ITEM_NAME) + "[" + code + "]";
packName = data.get(XT.PACK_NAME);
}
/**
* Copy constructor
*
* @param item
*/
public Item(Item item) {
code = item.code;
name = item.name;
packName = item.packName;
}}
When i pass null value to the method it is crashing, i don't know why my logic is wrong or what. 当我将null值传递给方法时,它崩溃了,我不知道为什么我的逻辑错了或什么。 Please help me in resolving this issue. 请帮助我解决此问题。
Check if item
is null instead of using a ternery operation. 检查item
是否为空而不是使用ternery操作。
if (item != null) {
logite("revertMessage()", "item " + item.code
+ " name : " + item.name );
}
else {
logite("revertMessage()", "item "
+ " name : " ); //weird message tho
}
Not sure if it will work, but it might 不知道它是否会工作,但是可能
Because item.name
can still be null. 因为item.name
仍然可以为null。
logite("revertMessage()", "item " + item == null ? "" : item.code
+ " name : " + name == null ? "" : item.name );
^ change to item
This is the same as calling it like this: 这与像这样调用它相同:
if(item == null) // ""
if(name == null) // "" , item.name() // item is still null
Change name
with item
and you are good to go. 用item
更改name
,您一切顺利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.