Master Object :- MBT_SFFB__Facebook_User__c
Detail Object :- MBT_SFFB__Facebook_Page__c
step 1) Inserting in Master object (only 1 record i wanna insert that is simple Insert). Inserting into MBT_SFFB__Facebook_User__c (User's Name) before the first insert statement i am calling facebook Graph API and retrieving the name of facebook user. Need to insert facebook user name in salesforce. step 2) Inserting in Detail Object (calling batch for inserting more than 1 records.) After inserting the name and ID in salesforce i want to insert facebook pages names and ID that are owned by that User.
Both insertion is in single method on page load.
Throws error :- Please commit or rollback before calling out
Is there anything i need to use ?? which is better approach ?
Please Find the code.
Http http =new Http();
HttpRequest req =new HttpRequest();
req.setEndpoint('https://graph.facebook.com/me?fields=id,name,picture&access_token='+token);
req.setmethod('GET');
HttpResponse res = http.send(req);
facebookuser objfacebookuser = new facebookuser(); // wrapper class
objfacebookuser=facebookuser.parse(res.getBody());
MBT_SFFB__Facebook_User__c objMBT_SFFB_Facebook_User = new MBT_SFFB__Facebook_User__c();
objMBT_SFFB_Facebook_User.MBT_SFFB__Facebook_ID__c = objfacebookuser.id;
objMBT_SFFB_Facebook_User.MBT_SFFB__Facebook_Name__c =objfacebookuser.name;
objMBT_SFFB_Facebook_User.MBT_SFFB__Image__c = objfacebookuser.picture.data.url;
objMBT_SFFB_Facebook_User.MBT_SFFB__Validated__c=true;
insert objMBT_SFFB_Facebook_User;
Http http =new Http();
HttpRequest req =new HttpRequest();
req.setEndpoint('https://graph.facebook.com/me?fields=accounts{picture,name}&access_token='+token);
req.setmethod('GET');
HttpResponse res = http.send(req);
facebookpages objallfacebookpages = new facebookpages();
objallfacebookpages=facebookpages.parse(res.getBody());
List<facebookpages.Data_Z> objallfacebookpageslist = new List<facebookpages.Data_Z>(); // wrapper class
objallfacebookpageslist = objallfacebookpages.accounts.data;
addfbpagestosystem c = new addfbpagestosystem(objfbpagestoinsert,objallfacebookpages.id); // batch Apex class
Database.executeBatch(c);
Code of batch apex:-
global void execute(Database.BatchableContext BC,List<sObject> scope)
{
for(facebookpages.Data_Z objfbpage :fbpages)
{
MBT_SFFB__Facebook_Page__c objrecfbpage = new MBT_SFFB__Facebook_Page__c(MBT_SFFB__Facebook_ID__c=id,MBT_SFFB__Facebook_Page_ID__c=objfbpage.id,MBT_SFFB__Facebook_Page_Name__c=objfbpage.name,MBT_SFFB__Image__c=objfbpage.picture.data.url,MBT_SFFB__Facebook_User_Relates_To_Page__c='wanna ID of first insertion');
objmtfbpage.add(objrecfbpage);
}
insert objmtfbpage;
}