0

The requirement is to import a tab separated text file and updated the records matching with some statuses then display success to for failure with the list of records.

I wrote the following VF and apex class

<apex:page standardController="Card_Request__c" extensions="CarerCardImportController" readOnly="false">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock>
            <apex:pageBlockSection columns="2">
              <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                <br/>
                <br/>
              <apex:commandButton value="Import Cards" action="{!importFile}"/>
            </apex:pageBlockSection>

            <apex:pageBlockTable value="{!updatedCardsList}" title="" var="cr">
                <apex:column value="{!cr.card.Carers_Card_Number__c}"/>
                <apex:column value="{!cr.card.Card_Status__c}"/>
                <apex:column value="{!cr.card.Carer_Sub_Status__c}"/>
                <apex:column value="{!cr.card.CC_Expiry_Date__c}"/>
                <apex:column value="{!cr.result}"/>
            </apex:pageBlockTable>

        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex class look like following

public with sharing class CarerCardImportController{

    public transient Blob csvFileBody {get; set;}
    public String csvAsString {get; set;}
    public String[] csvFileLines {get; set;}
    public List<Card_Request__c> cardToUpdate {get; set;}
    public static String INITIAL_STATUS = 'Issued';
    public static Map<Id, Card_Request__c> cardsUpdated {get; set;}
    public static List<CardWrapper> updatedCardsList {get; set;}
    public static Set<Id> cardIds {get; set;}

    public CarerCardImportController(){
        csvFileLines = new String[]{};
        cardToUpdate = new List<Card_Request__c>(); 
    }

    public CarerCardImportController(ApexPages.StandardController controller){
        cardsUpdated = new Map<Id, Card_Request__c>();
        updatedCardsList= new List<CardWrapper>();
        csvFileLines = new String[]{};
        cardToUpdate = new List<Card_Request__c>();
        cardIds = new Set<Id>();
    }


    public class CardWrapper{
        public Card_Request__c card {get;set;}
        public String result {get;set;}

        public CardWrapper(Card_Request__c card, String result){
            this.card = card;
            this.result = result;
        }
    }

    public void importFile(){
        try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
           //get all the card requests that approved before 
           List<Card_Request__c> approvedCards = [SELECT Id, Carers_Card_Number__c, Card_Status__c, DateIssued__c, Carer_Sub_Status__c 
                                        FROM Card_Request__c WHERE (Card_Status__c = 'Issued' AND Carer_Sub_Status__c = 'Waiting - Print Receipt')];

           cardToUpdate = new List<Card_Request__c>();
           //compare the cards with the received CSV
            for(Card_Request__c card : approvedCards){

                for(Integer i = 1; i < csvFileLines.size(); i++){
                    String[] csvRecordData = csvFileLines[i].split('\t');
                    if(card.Carers_Card_Number__c == csvRecordData[0]){
                        System.debug(csvRecordData[0]);
                        card.Card_Status__c = 'Active';
                        card.Carer_Sub_Status__c = 'Sent';
                        String cleanedCell = csvRecordData[1].trim();
                        String[] splitDate = String.valueOf(cleanedCell).split('/');

                        Date parsedIssuedDate = Date.newInstance(Integer.valueOf(splitDate[2]), Integer.valueOf(splitDate[1]), Integer.valueOf(splitDate[0]));
                        card.DateIssued__c = parsedIssuedDate;
                        cardToUpdate.add(card);
                        cardIds.add(card.Id);
                    }
                }   
            }
        }
        catch(Exception e){
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);     
            System.debug(e);
            System.debug(e.getMessage());
            System.debug(e.getCause());
            System.debug(e.getLineNumber());
        }

        try{
            Database.SaveResult[] results = Database.update(cardToUpdate);

                cardsUpdated = new Map<Id,Card_Request__c>([SELECT Id, Card_Status__c, Carer_Sub_Status__c, Application__c, Carers_Card_Number__c, CC_Expiry_Date__c
                                FROM Card_Request__c WHERE Id IN :cardIds]);                 

            for(Integer i = 0; i < results.size(); i++){
                if(results[i].isSuccess()){
                    Card_Request__c card = cardsUpdated.get(results.get(i).getId());
                    updatedCardsList.add(new CardWrapper(card, 'SUCCESS'));
                }else if (!results.get(i).isSuccess()){
                    String errors = '';
                    for(Database.error err : results.get(i).getErrors()){
                        errors += err.getStatusCode() + ': ' + err.getMessage() + '\n';
                    }
                    Card_Request__c card = cardsUpdated.get(cardToUpdate.get(i).Id);
                    updatedCardsList.add(new CardWrapper(card, errors));
                }
            }
        }
        catch(Exception e){
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data');
            ApexPages.addMessage(errorMessage);     
            System.debug(e);
            System.debug(e.getMessage());
            System.debug(e.getCause());
            System.debug(e.getLineNumber());
        }  
    }
}

it come up with attempt to de-reference a null object error at line where i'm adding the id to cardIds Set can some please help to get rid of this problem.

1
  • Can you try to remove static from cardIds – Tushar Sharma Sep 25 '18 at 5:09
1

You haven't instantiated the cardIds set in context of the importFile method. Add

cardIds = new Set<Id>(); 

somewhere before or in your try block (around line 37).

4
  • 2
    I have instantiated in the constructor – Mohammed Imran Sep 25 '18 at 4:08
  • Ah. I see that. Were you able to get this working? – Shane Steinfeld Sep 30 '18 at 21:31
  • Yes got it working by instantiating updatedCardsList within try. – Mohammed Imran Oct 1 '18 at 2:36
  • Ah -- makes sense. It's static. Just needed to instantiate it inside the importFile method. Cool! – Shane Steinfeld Oct 1 '18 at 3:32

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.