抛出NullPointer异常

时间:2016-01-19 05:28:30

标签: java exception exception-handling nullpointerexception

好的,所以我正在阅读已经在这里询问NPE的内容,但我似乎无法找到任何有助于我的代码的内容。它说它被.searchCollection(COLLECTION_NAME)抛出。

public class PantryDataStorage {

private static final String COLLECTION_NAME = "pantry";
private static HashMap<String, PantryItem> pantry = getDatabaseItems();
private static String API_KEY = "c3672b0c-b96c-4145-8b75-bd6895b5458e";
private static OrchestrateClient client = new OrchestrateClient(API_KEY);
ShoppingItem shoppingItem = new ShoppingItem();



public static void savePantryItem(String itemName, PantryItem updatedPantryItem){

    pantry.put(itemName, updatedPantryItem);
    client.kv(COLLECTION_NAME, itemName).put(updatedPantryItem).get().getKey();

}

public static void deletePantryItem(String itemName){

    pantry.remove(itemName);
    client.kv(COLLECTION_NAME, itemName)
    .delete()
    .get();
}

public static HashMap<String, PantryItem>getDatabaseItems(){

    SearchResults<PantryItem> result = client
            .searchCollection(COLLECTION_NAME)
            .limit(100)
            .get(PantryItem.class, "*")
            .get();

    Iterator<Result<PantryItem>> iterator = result.getResults().iterator();
    HashMap<String, PantryItem> listHash = new HashMap<String, PantryItem>();

    while(iterator.hasNext()){
        PantryItem pantryitem = iterator.next().getKvObject().getValue();
        listHash.put(pantryitem.getItemName(), pantryitem);
    }
    return listHash;
}
public static boolean itemConsists(String itemName){

    pantry.containsKey(itemName);
    return true;
}

public static void iteratorMethod(){
    Iterator<PantryItem> pantryItemIterator = pantry.values().iterator();

    while (pantryItemIterator.hasNext()) {
        System.out.println(pantryItemIterator.next());
    }
 }

}

2 个答案:

答案 0 :(得分:0)

savePantryItem开始,您正在使用client变量,并且在此方法和其他方法之外的任何地方都没有声明或初始化。考虑将client声明为私有实例变量。

答案 1 :(得分:0)

所以在你的代码中,当getDatabaseItems()调用OrchestrateClient时,客户端尚未初始化。这就是你获得NPE例外的原因。

要避免这种情况: 1)您可以添加条件以检查客户端是否为空 要么 2) 您按以下顺序声明您的成员变量:     private static String API_KEY =“c3672b0c-b96c-4145-8b75-bd6895b5458e”;     private static OrchestrateClient client = new OrchestrateClient(API_KEY);     private static HashMap pantry = getDatabaseItems();

如果尚未通过先前的对象创建初始化初始化,则初始化的顺序是静态的。