+ Start a Discussion
DDayDDay 

Getting values from List<sObject>

Hello,

 

Just started using Apex today and I'm having trouble using List<sObject>. Here is my class:

 

 

public class Settings {

private List<sObject> info;

 

public Settings() {

info = [Select Id, API_Key__c, Password__c, Phone_No__c, Recording_Phone_Number__c, Time_Zone__c from Settings__c];

}

 

public String getKey() {

//String key = [SELECT API_Key__c FROM Settings__C].api_key__c;

String key = info.api_key__c;

return key;

}

}

 

The line commented out in the getKey method works fine. However, trying to use info.api_key__c gives me the following error:

 

   Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST:SObject at line 10 column 22

 

How can I access individual values in the info List object?

 

Thanks,

Dan 

 

 

Message Edited by DDay on 06-04-2009 01:12 PM
philbophilbo

Hey,

 

Couple of things:

 

Presumably you are trying to extract one single Settings__c record.  Unless you're 100% absolutely certain you are never going to have more than one such record in your system, you should constrain your query so that it returns one record, or grab the zero'th returned record, and assign it to a SObject variable, not a List<SObject> list.

The generic SObject class doesn't know anything about the particulars of the actual object it's representing, so instead of going 'info.api_key__c' (assuming at this point, info is a SObject and not a List<SObject>), you have to either cast it or use the SObject get method:

 

( (Settings__c)info ).api_key__c

or

String.valueOf ( info.get ( 'api_key__c') )

 

Unless you're doing some funky stuff beyond what you've posted, you can probably just make 'info' a Settings__c variable instead of a SObject variable; then 'info.api_key__c' works fine.


Hope this helps!

Message Edited by philbo on 06-04-2009 04:52 PM
DDayDDay

Hi Phil,

 

That was exactly what I was looking for, thanks for the help!

 

What did you mean by "you can probably just make 'info' a Settings__c variable instead of a SObject variable"? 

 

Dan 

philbophilbo

I mean, instead of declaring your 'info' var as 'SObject info;' (note: not a list!  :) ) , you can declare it as 'Settings__c info;'.  If you do so, then you can directly access the Settings__c fields you've queried, as members of the var; i.e. 'info.api_key__c' will work correctly.