0

I have below line where I am getting Error as mentioned in subject header. Can some let me know the reason? Ideally it should return Email value.

String Emailing1 = [SELECT Email 
                    FROM User 
                    WHERE ID=:mycontact.Rep_abv__r.ManagerID].Email;
5

You tried to use the result of SOQL query in your code, but this result is not guarantied. In some case your query can return null. So, when you tried to use null.Email you got this error.

To fix it you need to check that query has returned an actual result.

User user1 = [SELECT Email 
              FROM User 
              WHERE ID=: mycontact.Rep_abv__r.ManagerID];
if (user1 != null) {
    String Emailing1 = user1.Email;   
}
1

Try

String Emailing1 = [select Email from User where ID=:mycontact.Rep_abv__r.ManagerID LIMIT 1].Email;

But you have to make sure the query returns values. Better you check the result for null and assign your values.

User myUser = [select Email from User where ID=:mycontact.Rep_abv__r.ManagerID LIMIT 1];
String Emailing1 = (myUser != null) ? myUser.Email : '';
4
  • You are trying to get size of a sobject rather than list - this will fail to compile. Using something like user[] myUser = [...] and then assigning using myUser[0].Email would be better.
    – dzh
    Sep 8 '15 at 9:33
  • Best would be just using ( ! myUser.isEmpty() ) ? ... : ... ;
    – dzh
    Sep 8 '15 at 9:35
  • agreed, I've added typical check for query result mistakenly
    – highfive
    Sep 8 '15 at 9:37
  • 1
    limit 1 is also redundant as IDs are unique! :)
    – dzh
    Sep 8 '15 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.