Skip to main content
Hi,

I have the following code

Opportunity oppty = new Opportunity();

oppty.Name='123';

insert oppty;

Product2 pr = new Product2();

pr.Name = '123';

pr.Description = 'my product';

myJunctionObject obj = new myJunctionObject();

obj.Product2.id  = pr.id; //

obj.Opportunity.id  = oppty.id;

insert obj;

I am getting the error - Attempt to dereference a null object.Null pointer exception at 'insert obj;'

Can anyone suggest a solution to overcome this

Thanks,

Abhilash
3 answers
  1. Mar 23, 2018, 6:02 AM
    Hi Abhilash,

    You are using obj.Product2.id, you need to use obj.Product2Id as per bellow code.

    (Same for obj.Opportunity.id

    , it should be obj.OpppurtunityId)

    myJunctionObject obj = new myJunctionObject();

    obj.Product2Id = pr.id;

    obj.OpportunityId = oppty.id;

    insert obj;

    Additionally you missed insert statement for Product2 in your code.

0/9000