+ Start a Discussion
jai.sjai.s 

System.NullPointerException: Attempt to de-reference a null object

Hi,

I am get error like: 
System.NullPointerException: Attempt to de-reference a null object
Class.SearchListController.getSObjectList: line 19, column 1     

public class SearchListController{
 
    public String objectName {get;set;}
    public List<String> objectFields {get;set;}
    public List<SObject> SObjectListToShow {get;set;}
    public SearchListController(){
        //objectName= 'MyObject__c';
        objectName= '';
        SObjectListToShow =new List<SObject>();
       // SObjectListToShow = getSObjectList();
    }
    
    public List<SObject> getSObjectList(){
    
    //Getting field list for the sObject 
        objectFields =  new List<String>();
        Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
        Schema.sObjectType sObjType = globalDescription.get(objectName);
        Schema.DescribeSObjectResult res = sObjType.getDescribe();  // In this line, iam getting error
 
         Map<String , Schema.SObjectField> mapFieldList = res.fields.getMap();
        for(Schema.SObjectField field : mapFieldList.values())
        {
            Schema.DescribeFieldResult fieldResult = field.getDescribe();
            if(fieldResult.isAccessible())
            {
                objectFields.add(fieldResult.getName());
            }
        }
 
        //Building Query with the fields
        Integer i = 0;
        String fieldsToFetch = '';
        Integer len = objectFields.size();
        for(String temp:objectFields)
        {
 
            if(i==len-1)
            {
                  fieldsToFetch = fieldsToFetch + temp;
            }
            else
            {
                  fieldsToFetch = fieldsToFetch + temp + ',';
            }
            i++;
        }
            String qryStr = 'Select ' + fieldsToFetch + ' From ' + objectName  ;
            return  Database.Query(qryStr);
    }
}

Please help sove this problem.

Regards,
Shaik
ManjunathManjunath
Hi,

Your objectName is set to "", So "globalDescription.get(objectName)" will return no value in sObjType.
As the value for the "sObjType" is null you are calling describe. So it is throwing the error.

Set some defalult value in "objectName" or  put a if condition to bypass the logic if it is blanik.

Regards,
MCS