0

I am using database.query method to retrieve 2 fields from account. But when i tried to fetch get the values of that fields i am getting null value. Can someone help me. Here totalValueFieldName is API Name of the account field.

  List<SObject> lstObj = Database.query(query);
            system.debug('lstObj -- '+lstObj);
            if(lstObj.size() > 0){
                Decimal totalVal = 0;
                Decimal actualVal = 0; 

                if(totalValueFieldName != null && totalValueFieldName.trim() != ''){ 
                    system.debug('totalValueFieldName top -- '+totalValueFieldName);
                    system.debug('lstObj[0].get  totalValueFieldName top -- '+lstObj[0].get(totalValueFieldName));
                    totalVal = Decimal.valueOf(String.valueOf(lstObj[0].get(totalValueFieldName)));

                } 
                actualVal = Decimal.valueOf(String.valueOf(lstObj[0].get(actualValueFieldName)));                     
                //Means only 1 API Name was supplied and field type is percentage
                if(totalVal == 0){
                    retVal = Integer.valueOf(actualVal );
                }else if (actualVal > 0){
                    retVal = Integer.valueOf( ( actualVal / totalVal ) * 100 );  
                } 

enter image description here

Thank you.

0

Are you 100% certain that the data is there? Regardless some defensive coding would be beneficial. You're getting a null pointer exception here:

actualVal = Decimal.valueOf(String.valueOf(lstObj[0].get(actualValueFieldName)));

I would check that lstObj[0].get(actualValueFieldName) is not null before calling Decimal.valueOf().

Perhaps something like this:

if(String.isNotEmpty(lstObj[0].get(actualValueFieldName))) { actualVal = Decimal.valueOf(String.valueOf(lstObj[0].get(actualValueFieldName))); }

| improve this answer | |
  • Thank you @Mathew McKenzie. It worked. Data for that record was not there.. – Aryan Feb 29 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.