1

I know I am missing something very small, but I cannot get my head around. This is what I've tried

public class SampleClass {
    public String currentUserId {get;set;}

    public SampleClass(){
       String currentUserId = [SELECT Id, Name FROM User WHERE Id =: UserInfo.getUserId()].Id;
    }

    public static void displayData(){
       System.debug('Current Id: ' +currentUserId);
    }
}

Error:

Line 9: Variable does not exist: currentUserId

2 Answers 2

6

You cannot access instance variable(currentUserId) in a static method(displayData).

Either you should declare currentUserId as static:

public Static String currentUserId {get;set;}

Or displayData as non static:

public void displayData(){
    System.debug('Current Id: ' +currentUserId);
}

Also you need not declare currentUserId two times. Avoid declareation inside constructor.

This is the working code:

public class SampleClass {
    public String currentUserId {get;set;}

    public SampleClass(){
        currentUserId = [SELECT Id, Name FROM User WHERE Id =: UserInfo.getUserId()].Id;
    }

    public void displayData(){
        System.debug('Current Id: ' +currentUserId);
    }
}

Note : If you only need current user's id only no need for a query.

You can get by:

currentUserId = UserInfo.getUserId();

Go through Static and Instance Methods, Variables, and Initialization Code for more details.

3
  • Hey @Reshma, when I've tried using static on both variable and the method, I am getting null from method displayData. Is this an expected behavior? Jan 3, 2019 at 14:50
  • 1
    If you are using static keyword declare and initialize variable in class level like public static string currentuserid = userinfo.getuserid();
    – Reshma
    Jan 3, 2019 at 15:18
  • 1
    Great. That worked. Jan 3, 2019 at 15:45
0
public static void displayData(){
  System.debug('Current Id: ' +currentUserId);
}

This method is static and you are trying to accessing non-static data member currentUserId in your static function. You cannot access non static members in static context.

Following things can be applied to fix this issue

  1. if you declare your variable as static data member, this issue will be fixed.
  2. Remove the static keyword from your function

You must log in to answer this question.

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