2016-11-20 53 views
-1

我正在做我使用Java和eBay SDK(API)的第一步。关于函数调用的java nullpointerexception

在此代码片段中,我尝试从eBay获取类别列表。

该调用似乎工作,我在gcResponse对象中得到一个很大的结果。 下一步是循环返回的类别。 类别以数组形式返回。 类型CategoryType的变量ct包含一个类别。 调试时,我可以看到正确填充了数据的CategoryType对象(名称,级别...)。

ct.leafCategory的值为'false',表示此类别不是叶类别。

但是,当我尝试通过getLeafCategory()函数访问此字段时,我得到一个空指针异常(它被APIException-catch块捕获)。

现在我想知道如何正确访问此字段(我想要返回的所有内容都是'false')。我无法直接访问该字段,因为它当然似乎是私人的。

这是否意味着NPE发生在leafCategory()函数内?但是除了'return leafCategory',函数还能做什么?

非常感谢给我一个提示!

ApiContext apiContext = getContext(env, siteID); 

    GetCategoriesCall call = new GetCategoriesCall(apiContext); 
    GetCategoriesResponseType gcResponse = null; 

    call.setParentCategories(new String[] {"3187"}); 

    call.setCategorySiteID(getSiteCode(siteID)); 

    call.setDetailLevel(new DetailLevelCodeType[] {DetailLevelCodeType.RETURN_ALL}); 

    try { 

     call.getCategories(); 
     gcResponse = call.getResponse(); 

     CategoryArrayType arr = gcResponse.getCategoryArray(); 

     CategoryType ct = new CategoryType(); 

     KMTgcResponse.categories = new KMTCategory[arr.getCategoryLength()]; 

     for (int i=0; i<arr.getCategoryLength(); i++){ 
      ct = arr.getCategory(i); 
      KMTgcResponse.categories[i] = new KMTCategory(); 
      KMTgcResponse.categories[i].ID = ct.getCategoryID(); 

      KMTgcResponse.categories[i].leafCategory = ct.isLeafCategory(); // NullPointerException here !!! 
      KMTgcResponse.categories[i].level = ct.getCategoryLevel(); 
      KMTgcResponse.categories[i].name = ct.getCategoryName(); 
      KMTgcResponse.categories[i].parentID = ct.getCategoryParentID(); 
     } 

     response.getCategoriesResponse = KMTgcResponse; 
     response.rc = 1; 

    } catch (ApiException e) { 
     e.printStackTrace(); 
     response.err_msg = Common.toString(e); 
     response.rc = -1; 
} catch (Exception e) { 
     response.err_msg = Common.toString(e); 
     response.rc = -1; 
    } 
} 
+0

显示堆栈跟踪,请 –

+3

*我得到一个空指针异常(它是由ApiException内-catch块*抓到:没有,那是不可能的'赶上(ApiException E)'不会赶上NullPointerEx ception。总是发布您询问的异常的完整堆栈跟踪。 –

+0

什么是CategoryType? – brummfondel

回答

1

如果KMTgcResponse.categories[i].leafCategoryboolean原始而不是Boolean对象和ct.isLeafCategory();返回空值(如,值不从API存在),那么你从拆箱的Booleanboolean得到NullPointerException异常,因为你不能分配null到原始。

REF:http://developer.ebay.com/devzone/javasdk-jaxb/docs/libref/com/ebay/soap/eBLBaseComponents/CategoryType.html#isLeafCategory()

在任何情况下,

阵列之上即环看起来很奇怪。实际上你可以这样做(假设这些类型匹配)

KMTgcResponse.categories[i] = arr.getCategory(i); 

或者,因为你只是指相同的阵列位置

KMTgcResponse.categories = arr; 

最起码,这是写的首选方式它

ct = arr.getCategory(i); 
KMTCategory kmtcat = new KMTCategory(); 
kmtcat.ID = ct.getCategoryID(); 
kmtcat.leafCategory = null == ct.isLeafCategory() || ct.isLeafCategory(); // temporary error fix 
// other values 
KMTgcResponse.categories[i] = kmtcat; // set the array 
+0

YES,这就是问题。我忽略了getLeafCategory()返回布尔值而不是布尔值。现在你能告诉一个血腥的初学者如何将布尔空值转换为原始布尔值false值吗? –

+0

大部分情况下,只需更新'KMTCategory'对应的值 –

+0

非常感谢! –