0

Thanks in advance. I have a batch apex code here. I want to insert the records into my custom object. what is the code for inserting the records.

global class WeatherForecastBatch implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.stateful{ 
   global Database.QueryLocator start(Database.BatchableContext BC) {
        String query='Select id,City__c from Weather_Forecast__c';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Weather_Forecast__c> scope) {
        List <Weather_Forecast__c> collectionofcity =[SELECT Id,City__c FROM Weather_Forecast__c];
        for(Weather_Forecast__c w:collectionofcity) {
         try {
           Http http = new Http();
            HttpRequest request = new HttpRequest();
            PageReference endPoint = new PageReference('https://api.weatherbit.io/v2.0/current');
            endPoint.getParameters().put('city', w.City__c);
            endPoint.getParameters().put('key','d3730680f92f4b398eef44fe5e0b8661');
            request.setEndpoint(endPoint.getUrl());
            request.setMethod('GET');
            HttpResponse response = http.send(request);
              if (response.getStatusCode() == 200){
                 Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                List<Object> data = (List<Object>)results.get('data');
                for(Object temp: data) {
                Map<String, Object> item_data = (Map<String, Object>)temp;
                Weather_Forecast__c weath = new Weather_Forecast__c();
                weath.temperature__c = (decimal)item_data.get('app_temp');
                system.debug(weath.temperature__c);
                }
              }
            }catch(Exception e){
                    System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
                }
        }
       }
 global void finish(Database.BatchableContext BC){
         }
    }
0

Firstly initialize the list before for loop. Then add the object into the list inside for loop. Use DML on list outside of for loop so that you can avoid DML limit.

You can use below code

global void execute(Database.BatchableContext BC, List < Weather_Forecast__c > scope) {
List < Weather_Forecast__c > collectionofcity = [SELECT Id, City__c FROM Weather_Forecast__c];
List < Weather_Forecast__c > listWeather = new List < Weather_Forecast__c>();
for (Weather_Forecast__c w: collectionofcity) {
    try {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        PageReference endPoint = new PageReference('https://api.weatherbit.io/v2.0/current');
        endPoint.getParameters().put('city', w.City__c);
        endPoint.getParameters().put('key', 'd3730680f92f4b398eef44fe5e0b8661');
        request.setEndpoint(endPoint.getUrl());
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 200) {
            Map < String, Object > results = (Map < String, Object > ) JSON.deserializeUntyped(response.getBody());
            List < Object > data = (List < Object > ) results.get('data');
            for (Object temp: data) {
                Map < String, Object > item_data = (Map < String, Object > ) temp;
                Weather_Forecast__c weath = new Weather_Forecast__c();
                weath.temperature__c = (decimal) item_data.get('app_temp');
                listWeather.add(weath);
            }
        }
    } catch (Exception e) {
        System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber());
    }
}
insert listWeather;

}

4
  • Thanks@Chetan Nandre. but iam new to the code development. can u please explain with sample code.I cannot understand what you are trying to say.
    – Aishwarya
    Sep 6 '19 at 5:19
  • Whenever you want to insert records in apex use list for DML, else you will get salesforce limitation while inserting single records inside for loop. Sep 6 '19 at 5:23
  • can u please highlight the line where to initialize the list and add the object? and iam getting the error as [ EXCEPTION_THROWN [12]|System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out]
    – Aishwarya
    Sep 6 '19 at 5:27
  • You cannot perform a DML operation prior to a callout. All the DML operations should be invoked only after you are done with callouts. So, make a webservice callout first and then save the request. Sep 6 '19 at 5:45
0

If you pay your attention over here, You have created an instance variable of Weather_Forecast__c object which is absolutely correct. Then you are trying to assign a field value of temperature__c in your sobject instance variable.

Weather_Forecast__c weath = new Weather_Forecast__c();
weath.temperature__c = (decimal)item_data.get('app_temp');
system.debug(weath.temperature__c);

What you have missed?

You have not written any dml statement to insert the record. You need to know about the DML operation in apex. Using DML, you can insert new records and commit them to the database. Similarly, you can update the field values of existing records.

A sample example would be:-

Account[] accts = new List<Account>();
for(Integer i=0;i<3;i++) {
    Account a = new Account(Name='Acme' + i, 
                            BillingCity='San Francisco');
    accts.add(a);
}
insert accts; 

Read more about them here:-

  1. Inserting and Updating Records
  2. Database Class

Note:- As you are dealing with for loops, Apex has governor limits. If you hit them, Your whole transaction will get failed.

So, You need to avoid writing dml statements inside the for loops. As you can see in the example above, I have initialised a list of Account where i am storing all the accounts to be inserted. And the dml statement exist outside the for loop.

Learn all the best practise to be follow in apex here:- Apex Code Best Practices

1
  • for(Integer i=0;i<3;i++) { Weather_Forecast__c a = new Weather_Forecast__c(City__c='city' + i, Temperature__c =decimal.valueof('Temperature')); acts.add(a); } insert acts; the above declaration is correct
    – Aishwarya
    Sep 6 '19 at 5:56

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.