Can someone please tell my why I’m getting a null pointer exception with this code? In my Nutrition class, I implement a hash map:
public class Nutrition implements Serializable{
private final String TAG = Nutrition.class.getSimpleName();
//class variables
...
//hash map declaration
HashMap<String, String> nutrition;
public Nutrition(JSONObject jo) throws JSONException{
//create hash map
this.nutrition = new HashMap<String, String>();
//place data in hashmap
this.serving_size = jo.optString("serving_size");
nutrition.put("serving_size", serving_size);
Log.i(TAG, serving_size + " : Serving Size");
....
}
//method to get hashmap
public HashMap<String, String> getHashMap(){
return nutrition;
}
Then in another class, I call getHashMap() and I get a null pointer:
//nutrition item
Nutrition nutritionInfo = dish.getNutrition();
nutInfo = nutritionInfo.getHashMap();
Can someone tell me what I’m doing wrong and how I can fix it?
The second line will throw an NPE if dish.getNutrition() returns null.
Since you haven’t shown us the code in the Dish class, I would assume it occurs here.