Attempt to de reference a null object error - salesforce

On line acct.AmountX__c += amtX this and acct.AmountY__c += amtY this it is giving me an error. The trigger is on after insert and after update. When i am inserting any record in contact then it is giving me an error i don't know why. Why should 'acct' be initialized if i am not wrong this error comes when you have not initialized something.
public class ContactAccountRollUpAmount {
public static void onAfterInsertOrUpdate(List<Contact> cont){
contAccRollUpAmount(cont);
}
public static void contAccRollUpAmount(List<Contact> contactList){
List<Contact> cont = new List<Contact>([Select AccountId, Amount_Type__c, Amount__c
from Contact
where id in: contactList]);
List<Account> accList = new List<Account>([Select id, AmountX__c, AmountY__c
from Account Limit 50000]);
List<Account> accListToUpdate = new List<Account>();
for(Account acct: accList){
Double amtX = 0;
Double amtY = 0;
system.debug('#########'+acct);
for(Contact con: cont){
if(con.AccountId == acct.Id){
if(con.Amount__c != NULL){
if(con.Amount_Type__c == 'AmountX'){
amtX = amtX + con.Amount__c;
} else if(con.Amount_Type__c == 'AmountY'){
amtY = amtY + con.Amount__c;
}
}
}
}
if(amtX != NULL){
acct.AmountX__c += amtX;
}
if(amtY != NULL){
acct.AmountY__c += amtY;
}
accListToUpdate.add(acct);
}
if(accListToUpdate.size()>0){
update accListToUpdate;
}
}
}

The problem is not that the 'acct' is not initialized, its the field 'AmountX__c' and 'AmountY__c'.
As I can see you have queried max of 50000 records, out of these records some of them have 'Null' values for the above two fields.
I suggest please check whether the above two fields have 'Null' values for some records or not.

Related

Maximum view state size limit (135KB) exceeded

This code has been working fine for years.
public PageReference chkinst() {
i=0;
integer j=0;
Set<String> aSearchSet = new Set<String>();
List<Lead> lList = ui;
for (Lead l : lList) {
aSearchSet.add(l.company);
}
Account[] accountToCreate = new Account[]{};
Map<String,Account> companyToAccountMap = new Map<String,Account> ();
for (Account a: [select id, Name from Account where name IN :aSearchSet])
companyToAccountMap.put(a.name,a);
for (Lead l : lList) {
if (!companyToAccountMap.containsKey(l.company)){
Account act = new Account(Name = l.Company , Country__c = l.Country__c );
accountToCreate.add(act);
j = j +1;
}
}
insert accountToCreate;
if(j == 0) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'All leads have correct institution names'));
} else{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,j + ' Institutions created'));
}
return null;
}
Today, it gave me the following error:
Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 135.078KB
Does anyone know why?
Thanks,
It's hard to tell from this code snippet. But if I had to guess. It looks like your companyToAccountMap is a class level variable, and it's probably returning more records now then it used to. If you don't need that map anywhere else in the controller, I would move it to a method level or make it transient.

List has no rows for assignment

Can any one help me in solving this error:List has no rows for assignment to SObject
Class at line :
        
qName = [select Row_Id__c, Name from Ccon__c where Id = :ApexPages.currentPage().getParameters().get('id')].Row_Id__c;
Test Class line :
Controller  controller1  = new Controller(sc1);
This mean your query is returning no result (So the list is empty and then when casting into an Sobject there is not item to take).
qName = [select Row_Id__c, Name from Ccon__c where Id = :ApexPages.currentPage().getParameters().get('id')].Row_Id__c;
I would do it this way (to make sure in any case I will get value from my query if my ID is valid):
Id tempID = null;
if(ApexPages.currentPage().getParameters().get('id') != null)
{
tempId = ApexPages.currentPage().getParameters().get('id');
}
else{ //Error management
}
List<Ccon__c> recordsToProcess = new List<Ccon__c>();
if(tempID != null)
{
recordsToProcess = [select Row_Id__c, Name from Ccon__c where Id = :tempID];
}
else{ //Error management
}
//qName Declaration
if(!recordsToProcess.isEmpty())
{
qName = recordsToProcess[0].Row_Id__c;
}
else{ //Error management
}
if(qName == null)
{
//Error management
}
If you have more questions please feel free to ask. But as a best practice you might always ensure that your list is not empty before getting the record returned.
Thanks
HqSeO

Get element if from excel Sheet [duplicate]

This question already has answers here:
how to read all cell value using Apache POI?
(2 answers)
Closed 7 years ago.
I had created my script to validate my actual result and expected result , .
As there is too many link to validated script will get too much of coding m so i need to convert this into Data Driven Case ,.
Where Webdriver will get URL , xpath ,expected value from excel .
But dont know how to proceed , .
A demo code is much appreciated
Here is my current script :
public void test() throws Exception
{
String home_logo_url="158321";
String enough_talk_promo="1057406";
System.out.println("Check for home_logo_url");
driver.get(baseUrl);
String SiteWindow = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[#id='logo']/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String script = "return rlSerial;";
String value = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(value,home_logo_url);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
System.out.println("Check for enough_talk_promo");
driver.get(baseUrl + "/category/tournaments/");
driver.findElement(By.xpath("//*[#id='content']/div/div[4]/aside/div/div/p[1]/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String sr_enough_talk_promo = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(sr_enough_talk_promo,enough_talk_promo);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
}
How to iterated to each rows and get my test case run !!!
It is much helpful , if some one can convert my existing code to work on excel sheet .
Thanks
i was working on a project in Spring that read from an excel (.xls) and this was my code if can help
private List<String> extraire (String fileName) throws IOException {
List<String> liste = new ArrayList();
FileInputStream fis = new FileInputStream(new File(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = null;
rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
int i = 0;
row = (HSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
i++;
/**
* For verifying if a line is empty
*/
if (i % 29 == 0 || i == 1) {
while ( cellIterator.hasNext() && cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cell = cellIterator.next();
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String cellule = String.valueOf(cell.getNumericCellValue());
liste.add(cellule);
break;
case Cell.CELL_TYPE_STRING:
liste.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellule = " ";
liste.add(cellule);
break;
}
}
}
fis.close();
return liste;
}
in my controller :
List<String> liste = new ArrayList();
liste = extraire(modelnom);
for (int m=0, i=29;i<liste.size();i=i+29) {
if(i % 29 == 0) {
// i=i+29 : begin from the second line first coll
// m is line
m++;
}
String matricule = (String)liste.get(29*m).toString().trim();
float mat = Float.parseFloat(matricul); // From String to float
employe.setMatricule((int)mat); //reading mat as an int
// ... your Code
}

GAE, Local datastore does not create

I have no idea in what extend GAE is not easy to understand :(
My servlet manipulate a json string and then I'm trying to store it in datastore.
When I run the application I'm getting this output:
Jan 27, 2014 6:59:04 PM com.google.appengine.api.datastore.dev.LocalDatastoreService load
INFO: The backing store, D:\Android\IntelliJ IDEA\workspace\EyeBall\AppEngine\out\artifacts\AppEngine_war_exploded\WEB-INF\appengine-generated\local_db.bin, does not exist. It will be created.
1
2
3
4
5
7
***
***
***
***
***
8
9
Although it's mentioned that local_db.bin will be created but when I navigate to that directory the file is not there. Also, when I open http://localhost:8080/_ah/admin/datastore in browser nothing displays in Entity Kind drop down list.
So wtf happene to local_db.bin? Why it doesn't generates?
any suggestion would be appreciated. thanks.
==================
UPDATE:
I added my code based on request.
private static final String NO_DEVICE_ID = "FFFF0000";
private static final String SAMPLE_JSON = "{\"history\":[{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com\",\"url\":\"https://www.maybank2u.com.my/mbb/Mobile/info.do\",\"visits\":14},{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com\",\"url\":\"https://www.maybank2u.com.my/mbb/Mobile/adaptInfo.do\",\"visits\":4},{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com\",\"url\":\"http://www.maybank2u.com.my/mbb_info/m2u/public/personalBanking.do\",\"visits\":16},{\"date\":null,\"info\":null,\"title\":\"Maybank2u.com Online Financial Services\",\"url\":\"https://www.maybank2u.com.my/mbb/m2u/common/M2ULogin.do?action=Login\",\"visits\":52},{\"date\":null,\"info\":null,\"title\":\"‭BBC\",\"url\":\"http://www.bbc.co.uk/persian/\",\"visits\":16}]}";
private static final String QUERY_HISTORY_DEVICE = "SELECT m FROM HistoryDeviceJPA m WHERE m.userUUID = :keyword ORDER BY m.domain ASC";
private static final String QUERY_HISTORY = "SELECT m FROM HistoryJPA m WHERE m.pageAddress = :keyword";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// displayError(response, "The page doesn't support httpGet");
String deviceId = NO_DEVICE_ID;
String content = SAMPLE_JSON;
System.out.println("1");
HistoryBrowser historyBrowser = parseJson(content);
if(historyBrowser == null)
return;
System.out.println("2");
List<HistoryBrowser.BrowserInfo> historyList = historyBrowser.getHistory();
if(historyList == null)
return;
System.out.println("3");
List<HistoryDeviceJPA> historyDeviceJPAList = new ArrayList<HistoryDeviceJPA>(historyList.size());
for(int i=0; i<historyList.size(); i++) {
try {
HistoryBrowser.BrowserInfo browser = historyList.get(i);
HistoryDeviceJPA historyDeviceJPA = new HistoryDeviceJPA();
historyDeviceJPA.setUserUUID(deviceId);
historyDeviceJPA.setDomain(getDomainName(browser.getUrl()));
historyDeviceJPA.setPageAddress(browser.getUrl());
historyDeviceJPA.setPageTitle(browser.getTitle());
historyDeviceJPA.setPageVisits(browser.getVisits());
historyDeviceJPAList.add(historyDeviceJPA);
} catch (URISyntaxException e) {
System.out.println(e.getMessage());
}
}
System.out.println("4");
// get history of device from data store
EntityManager em = EMF.get().createEntityManager();
Query q = em.createQuery(QUERY_HISTORY_DEVICE).setParameter("keyword", deviceId);
#SuppressWarnings("unchecked")
List<HistoryDeviceJPA> dbList = (List<HistoryDeviceJPA>) q.getResultList();
System.out.println("5");
// If there is no result (shows there is no record for that device)
if(dbList == null)
addHistoryDeviceJPAToDs(historyDeviceJPAList);
else {
System.out.println("7");
// find each item in datastore and replace them if needed
// if current page visit is less ot equal than previous visit don't do anything (remove item form historyDeviceJPAList)
outerLoop:
for(int i=0; i<historyDeviceJPAList.size(); i++) {
HistoryDeviceJPA deviceItem = historyDeviceJPAList.get(i);
System.out.println("***");
for(int j=0; j<dbList.size(); j++) {
HistoryDeviceJPA dbItem = dbList.get(j);
if(deviceItem.getPageAddress().equalsIgnoreCase(dbItem.getPageAddress())) {
if(deviceItem.getPageVisits() > dbItem.getPageVisits()) {
long diff = deviceItem.getPageVisits() - dbItem.getPageVisits();
dbItem.setPageVisits(deviceItem.getPageVisits());
HistoryJPA historyJPA = findHistoryJPA(dbItem.getPageAddress());
historyJPA.setPageVisits(historyJPA.getPageVisits() + diff);
// update datastore
addHistoryDeviceJPAToDs(dbItem);
addHistoryJPAToDs(historyJPA);
// don't check other items of j list
break outerLoop;
}
}
}
}
System.out.println("8");
}
System.out.println("9");
// http://www.sohailaziz.com/2012/06/scheduling-activities-services-and.html
// https://dev.twitter.com/docs/api/1.1
// https://developers.google.com/appengine/docs/java/datastore/jdo/creatinggettinganddeletingdata?csw=1#Updating_an_Object
// http://en.wikibooks.org/wiki/Java_Persistence/Inheritance
}
and 6 is here:
private void addHistoryDeviceJPAToDs(List<HistoryDeviceJPA> list) {
System.out.println("6");
EntityManager em = EMF.get().createEntityManager();
try {
for (int i=0; i<list.size(); i++) {
System.out.println("=> " + i + " - " + list.get(i).toString());
em.getTransaction().begin();
em.persist(list.get(i));
em.getTransaction().commit();
}
} finally {
em.close();
}
}
after debug I found the problem is in this line:
List<HistoryDeviceJPA> dbList = (List<HistoryDeviceJPA>) q.getResultList();
if(dbList == null)
addHistoryDeviceJPAToDs(historyDeviceJPAList);
'dbList' is never null and it's size is 0 if there is nothing in datastore. That's why addHistoryDeviceJPAToDs method never invoked. By changing the code to following problem solved and local db created.
List<HistoryDeviceJPA> dbList = (List<HistoryDeviceJPA>) q.getResultList();
if(dbList == null)
return;
System.out.println("5");
// If there is no result (shows there is no record for that device)
if(dbList.size() == 0)
addHistoryDeviceJPAToDs(historyDeviceJPAList);
For other people who come across the same issue --
GAE will not create local_db.bin until you put data in the datastore. So if the file is not there, there is likely a bug in the application code.

Problem with the database WPF application it cannot add anything

I was trying to add new row to my database table and it seams that everything is going well in the application WPF and when i close the application the database has not changed(new record was not added in the database ) I tried to use dataadapters so here is my class that i use and the code behing
DD.cs
namespace WpfApplication2
{
class DD
{
private Database1DataSetTableAdapters.Table1TableAdapter _cpuAdapter = null;
protected Database1DataSetTableAdapters.Table1TableAdapter Adapter
{
get
{
if (_cpuAdapter == null)
_cpuAdapter = new Database1DataSetTableAdapters.Table1TableAdapter();
return _cpuAdapter;
}
}
[System.ComponentModel.DataObjectMethodAttribute
(System.ComponentModel.DataObjectMethodType.Insert, true)]
public bool AddCPU(string Naslov, string Avtor, string Lokacija, int Broj, string
Zabeleska, string Izdava)
{
Database1DataSet.Table1DataTable cpus = new Database1DataSet.Table1DataTable();
Database1DataSet.Table1Row cpu = cpus.NewTable1Row();
cpu.Naslov = Naslov;
if (Naslov == null) cpu.SetNaslovNull();
else cpu.Naslov = Naslov;
if (Avtor == null) cpu.SetAvtorNull();
else cpu.Avtor = Avtor;
if (Zabeleska == null) cpu.SetZabeleskaNull();
else cpu.Zabeleska = Zabeleska;
if (Izdava == null) cpu.SetIzdavaNull();
else cpu.Izdava = Izdava;
if (Broj == null) cpu.SetBrojNull();
else cpu.Broj = Broj;
if (Lokacija == null) cpu.SetLokacijaNull();
else cpu.Lokacija = Lokacija;
cpus.AddTable1Row(cpu);
int rowsAffected = Adapter.Update(cpus);
// Return true if precisely one row was inserted, otherwise false
return rowsAffected == 1;
}
HERE IS THE CODE BEHIND
it's an event on button click
string n, a, z,t,l;
int b;
l = txtLokacija.Text;
t = txtBroj.Text;
b = Convert.ToInt32(t);
n = txtNaslov.Text;
a = txtAvtor.Text;
z = txtZabeleska.Text;
t = "NONE";
txtZabeleska.Clear();
DD obj1=new DD();
obj1.AddCPU(n,a,l,b,z,t);
I found IT....when i finished the application and published then it seemed everything ok the database was working properly..i;ve restarted the PC and the newly added record

Resources