1

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.

Nikhil PV
  • 1,014
  • 2
  • 16
  • 29
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – GhostCat Jul 20 '16 at 12:05
  • @GhostCat this is correct --> item == null ? "" : item.code – Nikhil PV Jul 20 '16 at 12:08
  • In general, that is a valid idea. Nonetheless you might create a little helper method for that; those repeated ?: expressions simply make it very hard to read the expression as a whole. – GhostCat Jul 20 '16 at 12:11
  • @GhostCat ok.. i will try to write separate logic for each one – Nikhil PV Jul 20 '16 at 12:12

2 Answers2

1

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

John Sardinha
  • 3,566
  • 6
  • 25
  • 55
0

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.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107