简体   繁体   中英

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.

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. Please help me in resolving this issue.

Check if item is null instead of using a ternery operation.

    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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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