NULL pointer using hashmap - java

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.
Nutrition nutritionInfo = dish.getNutrition();
nutInfo = nutritionInfo.getHashMap();
Since you haven't shown us the code in the Dish class, I would assume it occurs here.

Related

How do i add individual values to list within a hashmap?

I've looked at so many examples but can't quite grasp this.
I need to create a method that inserts new values into already populated lists within my hashmap. I can't for the life of me figure out how to do. Can anyone help as well as explain how it works?
I've already created methods that populate the maps etc. I just can't figure out how to create a method that inserts just values for particular keys.
import java.util.*;
public class Singles
{
// instance variables - replace the example below with your own
private Map<String, List<String>> interests;
/**
* Constructor for objects of class Singles
*/
public Singles()
{
// initialise instance variables
super();
this.interests = new HashMap<>();
}
}
This is a multi-map.
public class MultiMap {
private Map<String, List<String>> multiMap = new HashMap<>();
public void put(String key, String value) {
List<String> values = (this.multiMap.containsKey(key) ? this.multiMap.get(key) : new ArrayList<>());
values.add(value);
this.multiMap.put(key, values);
}
}

NullPointerException when checking null

Basically, I create a map to store a unique key and a list of items. at first the map is null so in my class dosomething im checking if the map is null but it returns an exception. Please see code below.
Does anyone know what i can do to fix this issue?
public class MyClass{
private static Map<String, List<MyList>> MyMap = null;
private static void doSomething(){
String myKey = "hello";
if(MyMap.get(myKey) == null ){ // Here is where i got the exception "java.lang.NullPointerException"
//do something
}
}
}
public class MyList{
// do my List
}
private static Map<String, List<MyList>> MyMap = null; // null here and not initialized
MyMap.get(myKey)
your MyMap is null so it is throwing NPE
Your MyMap is null. Do as below..
public class MyClass{
private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>(); // creating instance
private static void doSomething(){
String myKey = "hello";
if(MyMap.get(myKey) == null ){ // Here is where i got the exception "java.lang.NullPointerException"
//do something
}
}
}
public class MyList{
// do my List
}
Your MyMap is throwing the NullPointerException. This happens because you've explicitly set it to null:
private static Map<String, List<MyList>> MyMap = null;
Instead you should initialise MyMap first:
private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>();
you have to initialize your HasMap.
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
if(myMap.get("bla") == null){
//do somethig
}

Calling a method using reflection and return back the map

I am trying to call a method process in Sample Model class using reflection in Java. That method accepts a map of string and string and returns back the same thing, a map of string and string.
Below is my code, but somehow it gives me an exception everytime.
Map<String, String> test = new LinkedHashMap<String, String>();
try {
test.put("CGUID", "ABCD");
test.put("RESOURCEINDEX", "XYZ");
Method m = SampleModel.class.getDeclaredMethod("process", Map.class);
Object o = m.invoke(null, test);
}
This line- Object o = m.invoke(null, test); gives me Null Pointer Exception always.
Can anyone help me what wrong I am doing here?
Below is the method signature-
#Override
public Map<String, String> process(final Map<String, String> attributes) {
Map<String, String> newData = new LinkedHashMap<String, String>();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(entry.getValue()).append("$$$$").append(UUID.randomUUID().toString());
newData.put(entry.getKey(), sb.toString());
}
return newData;
}
Update:-
Class<SampleModel> consClass = SampleModel.class;
Map<String, String> test = new LinkedHashMap<String, String>();
try {
test.put("CGUID", "ABCD");
test.put("RESOURCEINDEX", "XYZ");
Method m = SampleModel.class.getDeclaredMethod("process", Map.class);
Object o = m.invoke(consClass, test);
}
Above code is also not working? It gives me exception as-
object is not an instance of declaring class
Your method is not static, you therefore need to provide an instance when calling invoke.
SampleModel instanceOfYourClass = ...// get an instance
Object o = m.invoke(instanceOfYourClass, test);
You could only pass null to the invoke call if the method was static. Read the javadoc explaining this here.
If m.invoke(null, test) throws NullPointerException, most likely the process method is not static.
If you don't have ability to change the signature of that method, you should pass an instance of the SampleModel to m.invoke instead of null.
Assuming that SampleModel constructor is public and has no arguments, and you don't need the instance itself for anything, like this:
m.invoke(new SampleModel(), test);

Create method get by name for list

I have the following class and that provide entity name with key and val of HashMap:
import java.util.LinkedHashMap;
public class ObjectStructure {
private String entityName;
private LinkedHashMap<String, String> keyVal;
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public LinkedHashMap<String, String> getKeyVal() {
return keyVal;
}
public void setKeyVal(LinkedHashMap<String, String> keyVal) {
this.keyVal = keyVal;
}
}
I have also list as follows
private static List<ObjectStructure> JsonObj = new ArrayList<ObjectStructure>();
Since I'm getting the JSON object which list I need method that provide list by name
(i.e. entityName can have many entries and I want for specific entity get
the list of the respective data). I guess I need to build new class for it but I'm not sure how to design it, any ideas?
You could work with a different map:
Map<String, Map<String,String>> entities;
The key of the outer map would be the entityName, the inner Map is the collection of key/value pairs. To get the key/value pairs for a named entity, simply do:
Map<String, String> keyValueMap = entities.get("MyEntity");
I'm not quite sure what you are asking,
but if your asking how to return a certain ObjectStructure by entityName from the arraylist,
then just loop through the ArrayList and compare your searchString with each ObjectStructure's entityName.
If your looking for a value inside of the ObjectStructure inside of the ArrayList then
search the ArrayList for the right ObjectStructure. Once found, search the ObjectStructure for the key you are looking for.

NullPointExeption when try to put variable to object in Java

I create object which contain feature geometry and attributes:
public class Feature {
Feature(String wkt) {
this.wkt = wkt;
}
private HashMap<Column, String> columnMap;
private String wkt;
public String getWKT() {
return wkt;
}
public void addAttribute(Column column, String value) {
columnMap.put(column, value);
}
public String getAttribute(String column) {
return columnMap.get(column) ;
}
public Map<Column, String> getAttributes(){
return columnMap;
}
}
Wkt is a geometry. ColumnMap is object contain a attributes as HashMap:
public class Column {
private String columnName;
Column(String columnName) {
this.columnName = columnName;
}
public String getName() {
return columnName;
}
}
Now i says:
columnList = new ArrayList<Column>(columns);
......
Feature feature= new Feature(WKT);
for(int p=0;p<columnList.size();p++){
for(int k=0;k<=ViewObject.getMIDInfo(totalObjects).length;k++){
if(p==k){
System.out.println("Column "+columnList.get(p).getName()+" Value "+ ViewObject.getMIDInfo(totalObjects)[k].toString());
//feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString());
}
}
}
And get output:
Column id Value 22
Column kadnumm Value "66-41-0707001-19"
So how i understand columnList and ViewObject.getMIDInfo(totalObjects) is not empty. After this i change :
//feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString());
to:
feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString());
And get exeption:
Column id Value 22
java.lang.NullPointerException
at objects.Feature.addAttribute(Feature.java:18)
at objects.MIFParser.findRegion(MIFParser.java:181)
at objects.MIFParser.instanceNextObject(MIFParser.java:66)
at Read.main(Read.java:40)
How i understand NullPointerException means that i try to use empty objects? Whats wrong?
P.s. Sorry my english can be terrible especially with title .
UPDATE
Okey i add this: this.columnMap = new HashMap<Column, String>(); in FEature class constructor.
But now i try to do:
System.out.println(feature.getAttribute("id")+" "+feature.getAttribute("kadnumm"));
and output:
null null
What can be wrong?
You didnt initialize your columnMap:
private HashMap<Column, String> columnMap = new HashMap<Column, String>();
addAttribute tries to put something on columnMap, but you don't create columnMap anywhere. You need to add to your Feature constructor:
Feature(String wkt) {
this.wkt = wkt;
this.columnMap = new HashMap<Column, String>(); // <=== The new bit
}
...or add an initialization to your declaration:
private HashMap<Column, String> columnMap = new HashMap<Column, String>();
// The new bit--- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Just declaring the member isn't sufficient, the member just refers to an object, and starts off null. You need to create the object for it to refer to and assign that object to it.
columnMap object is not initialized when you create a new instance of Feature. So it is null when you call columnMap.put(column, value); in addAttribute
instead of
private HashMap<Column, String> columnMap;
do
private HashMap<Column, String> columnMap = new HashMap<Column, String>();
You must initialize the map:
private HashMap<Column, String> columnMap = new HashMap<Column, String>();

Categories