[SalesForce] Attempt to de-reference a null object – list get set

I try to add objects from 'accbetween' to 'idlist' (see the code below):

public class SearchTestApex {

    public list <Fund__c> idlist {get;set;}

    public list <Fund__c> accbetween  = new list<Fund__c>();

    public String idsaved {get;set;}

    public String searchKey {get;set;}

    public SearchTestApex( ) {
    }

    public void search(){

        String searchquerybetween='SELECT Id, Product__r.Id, Product__r.Name, Date__c FROM Fund__c WHERE Code__c LIKE \'%'+searchKey+'%\' ORDER BY Product__r.Id, Date__c DESC';

        accbetween= Database.query(searchquerybetween);

        //Then, I simply try to add the first value of accbetween to idlist:

        idlist.add(accbetween[0]);

        }
    }

There is a VisualForce code which is supposed to display 'idlist' but it returns the error as follow:

Attempt to de-reference a null object

I assume I might have to initialize 'idlist' or there could be an incompatibility between these types of list. Why do I get this error? How can I fix it?

Best Answer

Your problem is you never construct idList, so when you call idList.add(...), you are really calling null.add(...). This situation leads to an attempt to de-reference a null variable.

If you want for some reason to only add one result from your SOQL to the list, then add LIMIT 1 to your String, and simply assign the query result to your property.

String soql = 'SELECT ... FROM Fund__c WHERE ... ORDER BY ... LIMIT 1';
idList = Database.query(soql);

If you don't like that approach, then you should instead instantiate a new list:

List<Fund__c> records = Database.query(...);
idList = new List<Fund__c>();
idList.add(records[0]);
Related Topic