function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
nduchnduch 

UserInfo.getUserId() returning null

HI,

I have a problem determining the current user id.

 

I am using String userid = UserInfo.getUserId() , but this is returning null for some reason.

 

Any ideas why? Is it because I am in development mode, and not user mode?

 

Many thanks for help!

Best Answer chosen by Admin (Salesforce Developers) 
Navatar_DbSupNavatar_DbSup

Hi,

      Use the below code to get user name.

 

User u = [select firstname from user where id=:userinfo.getuserid()];

string username = u.firstname;

All Answers

Navatar_DbSupNavatar_DbSup

Hi,

     its weird if you are getting null. At my end userinfo.getuserid() returns the user id.Please check your code in controller class to get current user id.

 

 

 

 

    

nduchnduch

This is my code:

 

public class SendEmailPageController {
{

  public String user_id {get; set;}

 

  public SendEmailPageController(ApexPages.StandardController controller)
    {

          user_id = UserInfo.getUserId();
          System.assertEquals(user_id, null);

    }

}

 

Of course I am getting AssertionError, since user_id is null

Navatar_DbSupNavatar_DbSup

Hi,

 

Have you checked in debug window? it seems this code fine. you have to use assertnotequals() instead of  assertEquals.

user_id will give you current user id.

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

nduchnduch

You are right, my assert method was wrong, getUserId() is returning my user id.

 

However, I cannot use the user id in a query - I want to find out the user name based on his user id:

 

String username = [SELECT Name FROM Contact WHERE Id = : UserInfo.getUserId() ].[0].Name;

 

I am getting this error:

 

System.ListException: List index out of bounds: 0

External entry point

nduchnduch

And if I change the query to: ( I remove the index 0)

 

username = [SELECT Name FROM Contact WHERE Id = '005U0000000Eu9fIAC'].Name;

 

I am getting this error:

 

System.QueryException: List has no rows for assignment to SObject

 

Basically for some reason my query based on non-null user id is returning nothing.

Navatar_DbSupNavatar_DbSup

Hi,

      Use the below code to get user name.

 

User u = [select firstname from user where id=:userinfo.getuserid()];

string username = u.firstname;

This was selected as the best answer
nduchnduch

Aaaaaaah, I was querying the Contact table instead of User table ....

 

Many thanks for your help, S_Jain!

 

:smileyvery-happy: