function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Trent MichaelsTrent Michaels 

Apex Class: Illegal assignment from List to List

Hello all,

I found some code on how to create an Apex Class that allows users to send an email to salesforce with a specific subject format to create tasks.

The problem is that this code seems to be a little old and I'm having some trouble updating it as I'm not overly familiar with Apex coding. 

 

global class clsInboundEmailHandler implements Messaging.InboundEmailHandler { 

	global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){ 
		Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); 
			
			string subject = email.Subject; 
			string userID = ''; 
			integer userIDNumber = 0; 
			string restOfSubject = ''; 
			if(subject.contains('-') == false){ 
				result.success = false; 
				return result; 
			} 
			list<String> subjectSplit = new list<String>(); 
			subjectSplit = subject.split('-'); 
			userID = subjectSplit[0]; 
			userID = userID.trim(); 
			if(userID.isNumeric() == false){ 
				result.success = false; 
				return result; 
			}else{ 
				userIDNumber = integer.valueOf(userID); 
			} 
			boolean firstOne = true; 
			for(string s : subjectSplit){ 
				if(firstOne){ 
						firstOne = false; 
					}else{ 
						restOfSubject += s; 
					} 
				} 
				
				//Now find the user 
				string userIDForTask = getUserIDForTask(userIDNumber); 
				if(userIDForTask == ''){ 
					result.success = false; 
					return result; 
				} 
				
				Task t = new Task(); 
				t.Subject = restOfSubject; //This is from the subject line 
				t.ActivityDate = date.today(); 
				t.Description = email.plainTextBody; //or email.htmlbody; 
				t.Priority = 'Normal'; 
				t.OwnerId = userIDForTask; //Set to owner 
				t.Status = 'Not Started'; 
				t.IsReminderSet = true; 
				t.ReminderDateTime = System.now() + 1; 
				insert t; 
				
				result.success = true; 
				return result; 
			} 
			
			private string getUserIDForTask(integer userIDNumber){ 
				list<boolean> userList = new list<boolean>(); 
			string userIDForTask = ''; 
			userList = [Select ID 
								From User 
								Where EmailTaskID__c = :userIDNumber]; 
			if(userList.size() <> 1){ 
				return ''; 
				}else{ 
					return userList[0].id; 
				} 
			} 
		}

The problem is at line 58, I am getting the error "Illegal assignment from List to List". I believe the error is related to the way userIDNumber is declared, but for the life of me I cannot figure out the solution.

Would anyone have any suggestions or a solution?

Thank you.
Best Answer chosen by Trent Michaels
Magesh Mani YadavMagesh Mani Yadav
Hi Trent,
Replace line 56 with the line below
list<User> userList = new list<User>(); 

All Answers

Magesh Mani YadavMagesh Mani Yadav
Hi Trent,
Replace line 56 with the line below
list<User> userList = new list<User>(); 
This was selected as the best answer
Nevlyn DSousa TicloNevlyn DSousa Ticlo
Hi Trent,

Ideally the results of a soql query can be stored as follows
1. a single SObject. eg. User u = [Select id from user where {some condition}];
2. a list of sObjects. eg. List<User> userList = [Select id from user where {some condition}];
3. an integer. eg. integer i = [Select COUNT from User where {some Condition}];

In your case
At line 56
list<boolean> userList = new list<boolean>();

can you change that to
list<User> userList = new list<User>();

This should solve your problem.

let me know if that works.
Trent MichaelsTrent Michaels
So the solution worked to resolve errors, but now I'm running into similar problems with the test class.
 
@isTest 
private class clsInboundEmailHandlerTest { 

	static testMethod void clsInboundEmailHandlerTest() { 
		// create a new email and envelope object 
			Messaging.InboundEmail email = new 
			Messaging.InboundEmail() ; 
			Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); 
			
			// setup the data for the email 
			email.subject = 'This is my subject'; 
			email.fromname = 'FirstName LastName'; 
			env.fromAddress = 'someaddress@email.com'; 
			email.plainTextBody = 'Body of the Email'; 
			
			Messaging.InboundEmailResult ierItem; 
			clsInboundEmailHandler emailProcess = new clsInboundEmailHandler(); 
			ierItem = emailProcess.handleInboundEmail(email, env); 
			
			system.assertEquals(false, ierItem.Success); //The subject did not start with a number 
	} 
	
	static testMethod void clsInboundEmailHandlerTest2() { 
		// create a new email and envelope object 
			Messaging.InboundEmail email = new 
			Messaging.InboundEmail() ; 
			Messaging.InboundEnvelope env = new 
			Messaging.InboundEnvelope(); 
			
			// setup the data for the email 
			email.subject = 'A-This is my subject'; 
			email.fromname = 'FirstName LastName'; 
			env.fromAddress = 'someaddress@email.com'; 
			email.plainTextBody = 'Body of the Email'; 
			
			Messaging.InboundEmailResult ierItem; 
			clsInboundEmailHandler emailProcess = new clsInboundEmailHandler(); 
			ierItem = emailProcess.handleInboundEmail(email, env); 
			
			system.assertEquals(false, ierItem.Success); //The subject did not start with a number 
	} 
	
	static testMethod void clsInboundEmailHandlerTest3() { 
		// create a new email and envelope object 
			Messaging.InboundEmail email = new Messaging.InboundEmail() ; 
			Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); 
			
			// setup the data for the email 
			email.subject = '1-This is my subject'; 
			email.fromname = 'FirstName LastName'; 
			env.fromAddress = 'someaddress@email.com'; 
			email.plainTextBody = 'Body of the Email'; 
			
			Messaging.InboundEmailResult ierItem; 
			clsInboundEmailHandler emailProcess = new clsInboundEmailHandler(); 
			ierItem = emailProcess.handleInboundEmail(email, env); 
			
			system.assertEquals(false, ierItem.Success); //The id in the subject line was not found 
	} 
	
	static testMethod void clsInboundEmailHandlerTest4() { 
		// create a new email and envelope object 
			Messaging.InboundEmail email = new Messaging.InboundEmail() ; 
			Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); 
			
			// setup the data for the email 
			email.subject = '1-This is my subject'; 
			email.fromname = 'FirstName LastName'; 
			env.fromAddress = 'someaddress@email.com'; 
			email.plainTextBody = 'Body of the Email'; 
			User u = CreateUser(1); 
			
			Messaging.InboundEmailResult ierItem; 
			clsInboundEmailHandler emailProcess = new clsInboundEmailHandler(); 
			ierItem = emailProcess.handleInboundEmail(email, env); 
			
			system.assertEquals(true, ierItem.Success); //The id in the subject line was not found 
			list<String> taskList = new list<String>(); 
			taskList = [Select ID, Subject, Description 
									From Task 
									Where OwnerID = :u.ID]; 
			system.assertEquals(1, taskList.size()); 
			system.assertEquals(taskList[0].Subject, 'This is my subject'); 
			system.assertEquals(taskList[0].Description, 'Body of the Email'); 
	} 
	
	private static User CreateUser(integer numberForEmail){	
				Profile p = [SELECT Id FROM profile WHERE name='System Administrator']; 
		User u = new User(alias = 'newSUser', email='newSAuser@testorg.com', 
			emailencodingkey='UTF-8', lastname='SATesting', languagelocalekey='en_US', 
			localesidkey='en_US', profileid = p.Id, 
			timezonesidkey='America/Los_Angeles', username='newSAuser@testorg.com', 
			CommunityNickname='CN'); 
		u.EmailTaskID__c = numberForEmail; 
		u.FirstName = 'TestUser'; 
				u.LastName = 'TestLastuser'; 
				insert u; 
				return u; 
		} 
	}

Line 79 is throwing the same error "Illegal Assignment from List to List"
Nevlyn DSousa TicloNevlyn DSousa Ticlo
Line 78
list<String> taskList = new list<String>();
change to
list<Task> taskList = new list<Task>();
Magesh Mani YadavMagesh Mani Yadav
Hi Trent,

You need to replace liine 78 with
list<Task> taskList = new list<Task>();
 
Trent MichaelsTrent Michaels
I can't beleive how wonderful you guys are. Thank you, that solved an issue that's been plaguing me for a few days!
Shajadi shaikShajadi shaik
Hi

im facing issue like below for the same above test class can anybody help me pls

At this line it throws error as below
Method does not exist or incorrect signature: void handleInboundEmail(Messaging.InboundEmail, Messaging.InboundEnvelope) from the type EmailHandlerTest


@isTest()
public class EmailHandlerTest {
    static testMethod void EmailHandlerTest() { 
        // create a new email and envelope object 
            Messaging.InboundEmail email = new Messaging.InboundEmail() ; 
            Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); 
            
            // setup the data for the email 
            email.subject = 'This is my subject'; 
            email.fromName = 'FirstName LastName'; 
            env.fromAddress = 'someaddress@email.com'; 
            email.plainTextBody = 'Body of the Email'; 
            
            Messaging.InboundEmailResult ierItem; 
            EmailHandlerTest emailProcess = new EmailHandlerTest(); 
            ierItem = emailProcess.handleInboundEmail(email, env); 
            
            system.assertEquals(false, ierItem.Success); //The subject did not start with a number 
    } 
Shajadi shaikShajadi shaik
 ierItem = emailProcess.handleInboundEmail(email, env); 
At this line it throws error as below
Method does not exist or incorrect signature: void handleInboundEmail(Messaging.InboundEmail, Messaging.InboundEnvelope) from the type EmailHandlerTest


 
Naveen AcharyaNaveen Acharya
Hi 
I have an error in getting checkbox can any one check below code:


Apexcontroller........................................................................................................................................................................................
public class xx {
   public class wrapContact
{
public sobject con {get; set;}
public Boolean selected {get; set;}
public wrapContact()
{

selected = false;
}
}


    
   

    
    public List<SelectOption> SizeOptions{get;set;}
    public string sql;
    private integer OffsetSize = 0; 
    private integer LimitSize= 10;
        public List<string> lstFlds {get;private set;}
     public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public String selectedObject {get; set;}
    public String selectedField {get; set;}
    public List<String> leftSelected {get; set;}
    public List<String> rightSelected {get; set;}
    Set<String> leftValues = new Set<String>();
    Set<String> rightValues = new Set<String>();
    public List<sObject> objFields {get; set;}
   // public List<sobject> nobject {get; set;}
   public List<sobject> listWrapContact {get; set;}

    public List<String> result {get;set;}
    
      Public Integer size{get;set;} 
    Public Integer noOfRecords{get; set;}
    
    Public boolean isExport{get; set;}
    
    public void processSelected() {

List<sobject> lstconToDelete = new List<sobject>();
for(wrapContact wcon: listWrapContact)
{
if(wcon.selected == true)

lstconToDelete.add(wcon.con);
}
}

if(lstconToDelete.size() > 0 )
{
Delete lstconToDelete;
}

}
    
    
     public xx () 
    {  
       listWrapContact = new List<wrapContact>();

list<sobject> con = setCon.getRecords();

for(sobject c : con)
{
if(setCon.getResultSize() == 0){
listWrapContact.add(new wrapContact(c));
}

}         
        
         size=5;
        SizeOptions = new List<SelectOption>();
        SizeOptions.add(new SelectOption('5','5'));
        SizeOptions.add(new SelectOption('10','10'));
        SizeOptions.add(new SelectOption('20','20'));
       SizeOptions.add(new SelectOption('50','50'));
       SizeOptions.add(new SelectOption('100','100'));
        selectedObject = 'account__c';
        isExport= false;
        leftSelected = new List<String>();
        rightSelected = new List<String>();
        //leftValues.addAll(Objectfields); 
    }
    
    
    public list<String> alphabet{
    get{                                                                                                                    //To display a list of alphabets on vf page 
        alphabet = new list<string>{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Others','All'};
            return alphabet;         
            }
    set;
}
    public String alphaSearchConct{get;set;}                                                    // To get commandlink parameter for alphabet selected
public Pagereference getalphaSearch(){                                                              //To update contact list as per the alphabet selected by the user

    if (alphaSearchConct=='All'){
      Records();
    }
    else{
      Records();
    }
    
    return null;
}  
    
    
     public PageReference reset() {
      PageReference supportedObject = new PageReference(System.currentPageReference().getURL());
      supportedObject.setRedirect(true);
      return supportedObject;
      }
    public void proceed(){
       //PageReference record = new PageReference(System.currentPageReference().getURL());
     // record.setRedirect(true);
      //return record;
   //     system.debug('2'+leftSelected);
     //   system.debug('3'+rightSelected);
  //      system.debug('4'+leftValues);
    //    system.debug('5'+rightValues);
    //    system.debug('6'+result);
        Integer i=0;
        String fieldsToFetch = '';
        for(String temp:result){
           Integer len = result.size();
           if(i==len-1){
              fieldsToFetch=fieldsToFetch + temp;
              //system.debug('ad'+fieldsToFetch);
           }
            else{
                fieldsToFetch = fieldsToFetch + temp + ',';
               // system.debug('ad2'+fieldsToFetch);
            }
            i++;
        }
         lstFlds = new List<String>();
        sql = ' SELECT ' + fieldsToFetch + ' FROM ' + selectedObject + ' ORDER BY CreatedDate DESC';
        
        system.debug('llsoql'+sql);
        //objFields = Database.Query(sql);
       // system.debug('ll'+objFields);
         // Set<string> setFlds = new Set<String>();
       // for(integer k=0;k<objFields.size();k++){
           // setFlds.addAll(objFields[k].getPopulatedFieldsAsMap().keySet());
        //}
        
    ///    lstFlds.addAll(setFlds););
       //  Records();
       
          
      //  return null;
        }
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null && sql!=null) {                
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(sql));
                system.debug('record query :'+ setcon);
                system.debug('recordss'+ setCon.getRecords());
                setCon.setPageSize(size); 
                system.debug('mapsize2'+ size);
                noOfRecords = setCon.getResultSize();
            }            
            return setCon;
        }
        set;
    }
    
     public PageReference refreshPageSize() {
        setCon.setPageSize(size);
         setCon = null;
         system.debug('mapsize'+ size);
         Records();
         
         setCon.setPageNumber(1);
         return null;
    }
    
        public void Records() {
            
           //
           proceed();
         // objFields =new list<sobject>();
         system.debug('setrecord'+setCon.getRecords());
           
        listWrapContact=setCon.getRecords();
            system.debug('ll'+listWrapContact);
            Set<string> setFlds = new Set<String>();
        for(integer k=0;k<listWrapContact.size();k++){
            setFlds.addAll(listWrapContact[k].getPopulatedFieldsAsMap().keySet());
        }
        system.debug('objlidt'+listWrapContact);
        lstFlds.addAll(setFlds);
            system.debug('setFlds'+setFlds);
           // return null;
    }
    
    
   
     
    
    public List<SelectOption> getObjectNames()
    {
        List<SelectOption> objNames = new List<SelectOption>();
        List<String> entities = new List<String>(schemaMap.keySet());
        objNames.add(new SelectOption('','--None--'));
        entities.sort();
        for(String name : entities)
        {
            objNames.add(new SelectOption(name,name));
        }
        return objNames;
    }
    
    public List<SelectOption> getObjectFields()
    {
        result = new List<String>();
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Schema.SObjectType ObjectSchema = schemaMap.get(selectedObject);
        Map<String, Schema.SObjectField> fieldMap = ObjectSchema.getDescribe().fields.getMap();
        List<SelectOption> fieldNames = new List<SelectOption>();
        for(String fieldName: fieldMap.keySet())
        {
            fieldNames.add(new SelectOption(fieldName,fieldName));
           // system.debug('x'+fieldName);
        }
        //system.debug('fileds Name : = '+fieldNames); 
                    return fieldNames;

    }
    public PageReference getSelect(){
     String temp = selectedfield;

         temp = temp.remove('[');
       
        temp = temp.remove(']');
    
      leftSelected  = temp.split(',');
      //leftSelected.add(selectedfield);
        //system.debug('a'+selectedfield);
        rightSelected.clear();
       
        for(String s : leftSelected){
            leftValues.remove(s);
            rightValues.add(s);
          //system.debug('rightvalues'+rightvalues);
         //system.debug('tr'+result);
        }
        return null;
    }
     
    public PageReference getDeselect(){    
        leftSelected.clear();
        
        for(String s : rightSelected){
            rightValues.remove(s);
            leftValues.add(s);
        }
        return null;
    }
     
    public List<SelectOption> getDeselectedValues(){
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
       objList.addAll(leftValues);
        objList.sort();
        for(String s : objList){
            options.add(new SelectOption(s,s));
        }
        return options;
    }
     
    public List<SelectOption> getSelectedValues(){
        
        List<SelectOption> options = new List<SelectOption>();
        List<String> objList = new List<String>();
        objList.addAll(rightvalues);
        objList.sort();
         //system.debug('objList'+objList);
         //system.debug('rightvalues'+rightvalues);
        for(String s : rightvalues){
       //    system.debug('Records'+ s );
            options.add(new SelectOption(s,s));
           result.add(s);
         //   system.debug('ttt'+result);
           // system.debug('ttt2'+options);
        }
        return options;
        
    }  
   
    
    public void previous()  
    {  
        setCon.previous(); 
        Records();
    }  
    public void next()  
    {  
        setCon.next(); 
         Records();
    }  
    public Void first()
    {
        setCon.first();
         Records();
    }
    public void last()
    {
        setCon.last();
         Records();
    }
   
public PageReference getExport()
{
    isExport=true;
    return null;
}
      
  
}
visualforce...........................................................................................................................................................................................................

<apex:page controller="xx"  readOnly="true" cache="true" contentType="{!IF(isExport = true, 'application/vnd.ms-execel#report.xls', '')}">
<apex:form >
    
    
    
    <apex:pageBlock >
    <apex:pageBlockSection >
        <apex:pageBlockSectionItem >
            <apex:outputLabel value="Select Object:- "/>
            <apex:actionRegion >
            <apex:selectList value="{!selectedObject}" size="1">
                <apex:selectOptions value="{!ObjectNames}"/>
                <apex:actionSupport event="onchange" rerender="myFields" />
                </apex:selectList>
                <apex:commandButton value="reset" action="{!reset}" ></apex:commandButton>
            </apex:actionRegion>
        </apex:pageBlockSectionItem>  
        </apex:pageBlockSection>
        <apex:panelGrid columns="3" id="myFields">
                <apex:selectList id="sel1" value="{!selectedfield}" multiselect="true" style="width:200px" size="10">
                     <apex:selectOptions value="{!Objectfields}"/>
            </apex:selectList>     
                     <apex:panelGroup >
                <br/>
                <apex:image styleClass="picklistArrowRight" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getSelect}" reRender="myFields"/>
                </apex:image>
                <br/><br/>
                <apex:image styleClass="picklistArrowLeft" value="/s.gif">
                    <apex:actionSupport event="onclick" action="{!getDeselect}" reRender="myFields"/>
                </apex:image>
            </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightSelected}" multiselect="true" style="width:200px" size="10">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
                     </apex:panelGrid>
        <apex:commandButton value="process" action="{!Records}"/>
      

        <div align="left">
        <apex:commandButton action="{!URLFOR($Action.Account.New)}" value="New Record" />
        <apex:commandButton id="button" value="Download CSV" action="{!getExport}" rendered="{!NOT(ISNULL(setCon))}"/>
            <apex:commandButton value="Delete Selected" action="{!processSelected}"/>

         </div> 
        <div align="right">
        <apex:panelGrid >
            <apex:repeat value="{!alphabet}" var="alph">
                <apex:commandLink value="{!alph} | " action="{!getalphaSearch}" reRender="shows">
                <apex:param name="a" value="{!alph}" assignTo="{!alphaSearchConct}"/>
                </apex:commandLink>
                </apex:repeat>
        </apex:panelGrid>
    </div>
         <apex:actionFunction name="refreshPageSize" action="{!refreshPageSize}" status="fetchStatus" reRender="shows"/>
        <apex:pageBlockTable value="{!listWrapContact}" var="rec" id="shows">
            <apex:column >
<apex:inputCheckbox value="{!rec.selected}"/>
</apex:column>
                <apex:repeat value="{!lstFlds}" var="fld">
                    <apex:column value="{!rec[fld]}"/>
   </apex:repeat>   
   </apex:pageBlockTable>  
   <div style="text-align:right">  {!setCon.pageNumber}  
   </div>
   <div style="text-align:left">
   <apex:selectList value="{!size}" multiselect="false" size="1" onchange="refreshPageSize();">
                    <apex:selectOptions value="{!SizeOptions}"/>
         </apex:selectList>  
        <div style="text-align:center">            
       <apex:commandButton value="first" rendered="{!setCon.HasPrevious}" action="{!first}" />
      <apex:commandButton action="{!Previous}"  value="Prev" rendered="{!setCon.HasPrevious}"/>  
      <apex:commandButton value="Next" rendered="{!setCon.HasNext}" action="{!Next}"/> 
      <apex:commandButton value="Last" rendered="{!setCon.HasNext}" action="{!last}" />              
           </div>              
        </div>
    </apex:pageBlock>
</apex:form>    
</apex:page>