2016-07-20 22 views
0

應用程序崩潰時出現空指針異常調用此方法並在第二個參數中傳遞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); 
} 

項目類是

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; 
}} 

當我通過空值到它崩潰,我不知道爲什麼我的邏輯是錯誤的或者是什麼方法。 請幫我解決這個問題。

+1

的可能的複製[什麼是空指針異常,怎麼解決呢?(http://stackoverflow.com/questions/218384/ what-is-a-nullpointerexception-and-how-do-i-fix-it) – GhostCat

+0

@GhostCat這是正確的 - > item == null? 「」:item.code –

+0

一般來說,這是一個有效的想法。儘管如此,你可能會爲此創建一個小幫手方法;那些重複的?:表達式使得整個閱讀表達式變得非常困難。 – GhostCat

回答

1

檢查item是否爲空而不是使用ternery操作。

if (item != null) { 
     logite("revertMessage()", "item " + item.code 
       + " name : " + item.name); 
    } 
    else { 
     logite("revertMessage()", "item " 
       + " name : "); //weird message tho 
    } 

不知道是否會工作,但它可能

+0

Thankyou它正在工作.. –

+0

很高興我幫助=) –

0

因爲item.name仍然可以爲空。

logite("revertMessage()", "item " + item == null ? "" : item.code    
      + " name : " + name == null ? "" : item.name); 
         ^change to item 

這是與調用它像這樣:

if(item == null) // "" 
if(name == null) // "" , item.name() // item is still null 

變化nameitem,你是好去。