+ Start a Discussion

System.NullPointerException: Attempt to de-reference a null object

hello friends,


I am facing an issue with Map<>.


Step1:- I have created a Map<> with list of products (which is getting from one object, say "Product").


Step2:- I am getting records which has product ID from another object (say "Purchase").


Step3:- I am looping through each record from Purchase and get the "ProductId"  and reference to the Map<> I have created from the "Product" object.


Issue :- If the ProductId is not there in the map<> it will through an error "System.NullPointerException: Attempt to de-reference a null object".


How can I avoid the ID's which are not in the Map<>? How can I identify that the ID is not in the Map before I make a refernce to the Map<>?


Thanks in advance.





before referring values from map  confirm if the key exists in map or not . Right way is 


if (MyMap.containsKey(yourKey) )

your code....... MyMap.get(yourKey);






thanks a lot!!! , it did work for me.