0

I was new to salesforce. I was try trying to update that account record name belong to me. I am getting System.NullPointerException: Attempt to de-reference a null object could some can help me here is my class

public class MyController {

private final Account account;

public MyController() {
     list<Account> account = [SELECT Id, Name, Site FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
}

public Account getAccount() {
    return account;
}

public PageReference save() {
    update account;
    return null;
}
}
4
  • What was the line number of the error? Also, how are you calling this, what does the VF page look like and where is it being executed from?
    – JimRae
    Commented Jan 8, 2014 at 2:57
  • Thanks jim for reply.when i click on button save on vf page .iam getting Error message is in expression '{!save}' in component <apex:commandButton> in page newcontoller1 .How to resolve this
    – user5161
    Commented Jan 8, 2014 at 3:10
  • are u have any account id on vf page where u call this class? According to me ur list of account return null value because there is no id found on page.
    – Tepsi
    Commented Jan 8, 2014 at 4:04
  • Thanks jim. so how can i get the id to my visual force page .can you explain me?
    – user5161
    Commented Jan 8, 2014 at 9:26

2 Answers 2

4

Your private variable account isn't being assigned a value anywhere, so it's null when you try and update it in the save() method:

private final Account account;

public MyController() {
    // this creates a variable called account local to this method, which is not visible elsewhere
     list<Account> account = [SELECT Id, Name, Site FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
}

You could try this:

public MyController() {
    // this creates a variable called account local to this method, which is not visible elsewhere
     list<Account> account = [SELECT Id, Name, Site FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
     this.account = account[0];
}

But personally I'd avoid using the same variable name (other than for things like loop indices) inside a single class, it's a recipe for confusion like this. Rename the list something else such as accountList. I also avoid naming variables with the names of objects for the same reasons, renaming account to acct or theAccount might not be a bad idea.

3

Just to add on top of the existing solution its always advisable to check the null values for example we can do below.

public Account getAccount() {
    if(account != null)   //Check if account has any value to return.
        return account;
    else
        return null;
}

public PageReference save() 
{
    if(account != null)   //Check if account has any value to update.
          update account;
    return null;
}

You must log in to answer this question.

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