2

I have two lists that I am trying to combine to get one list of pets available for adoption (not really, but it's less boring than reality):

List<puppy> puppies = [SELECT Color, Name, Age, PetStores__r.Location, PetStores__r.Section FROM puppy];

List<kitten> kittens = [SELECT Color, Name, Age, PetStores__r.Location, PetStores__r.Section FROM kitten];

I'm running through all results in kitten and casting them to the superior puppy category. But I am getting stuck on figuring out how to add the PetStores fields to the puppy list.

for (kitten k : kittens){
    Puppy p = new Puppy();
    p.Color = k.Color;
    etc
    p.PetStores__r.Location = k.PetStores__r.Location; //This is where I am getting lost. Is this possible?
    puppies.add(p);
}

The above gives me a de-reference a null object error on the noted line. Is there something easy that I'm missing? Thanks!

1

1 Answer 1

1
p.PetStores__r.Location = k.PetStores__r.Location; 

PetStores__r needs to be populated first:

if(p.PetStores__r == null) {
  p.PetStores__r = new PetStore__c();
}
p.PetStores__r.Location = k.PetStores__r.Location;
3
  • If the goal is to save to the database, this would never work, right?
    – Adrian Larson
    Commented May 3, 2017 at 16:28
  • Thank you! This got me exactly what I needed - though I will not be saving anything, per Adrian's question.
    – mplax
    Commented May 3, 2017 at 16:31
  • @mplax Glad I could help! As Adrian set, remember you'd have to set the PetStores__c field to the correct PetStore__c Id if you did want to save to the database, but that's about it.
    – sfdcfox
    Commented May 3, 2017 at 16:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .