You need to sign in to do that
Don't have an account?
kumar_arun
System.NullPointerException: Attempt to de-reference a null object: Class.OpportunityUtil.createDefaultProduct: line 28,
Hi, I am new in Apex , please let me know where is the problem in this code. code does not have compile time error. when i trying to save record then it show the error "System.NullPointerException: Attempt to de-reference a null object: Class.OpportunityUtil.createDefaultProduct: line 28, column 1" . Please Help
Thanks.
Thanks.
public class OpportunityUtil { public static void assignPriceBook(Opportunity[] scope) { Pricebook2 pb = [SELECT Id FROM Pricebook2 WHERE Name = 'Standard']; for(Opportunity record:scope){ record.Pricebook2Id = pb.Id; } } public static void createDefaultProduct(Opportunity[] scope) { map<string, pricebookentry> pbs = new map<string, pricebookentry>(); pricebook2 pb = [select id from pricebook2 where name = 'Standard']; opportunitylineitem[] oli = new opportunitylineitem[0]; for(Opportunity record:scope){ pbs.put(record.name, null); // or however we are determining the product. } // Find relevant entries for(PricebookEntry record:[select id,unitprice,product2id,product2.name from pricebookentry where product2.name in :pbs.keyset() and pricebook2id = :pb.id]) { pbs.put(record.product2.name, record); } for(Opportunity record:scope){ oli.add(new opportunitylineitem( opportunityid = record.id, unitprice = pbs.get(record.name).unitprice, quantity = 1, pricebookentryid = pbs.get(record.name).id)); } insert oli; } }
trigger CreateOpportunityLineItem on Opportunity (before insert,after insert) { if(Trigger.isbefore) opportunityUtil.assignPriceBook(Trigger.new); if(Trigger.isafter) opportunityUtil.createDefaultProduct(Trigger.new); }
In line 21 ,what is product2 field ? to which object is it related to?
So in line 28, pbs.get(record.name).unitprice , the key "record.name" is not matching with available key set loaded in the map in line 22 .
So figure out why key is not present from the key set loaded in line 22.
Mark this ans as kudos if it helpful to you
So in line 22 , you inserting Product name as key in the map
but in 28 line , you are trying to retrieve opportunity name as key , so it results in null .
whenever you access null object , it will results to deference to null pointer error .
Mark this ans as kudos if it helpful to you
unitprice = pbs.get(record.name).unitprice, => unitprice = null.unitprice,
Hence, null pointer exception.