Attempt to de-reference a null object: Salesforce - apex-code

I am trying to submit data to a server where it is picked and stored in salesforce. The error I am getting is "Attempt to de-reference a null object" at the server. so I am wondering what the problem is...
Below is the sample code:
public static List<String> processAgentVisitSurvey(ProcessSurveySubmission.SurveySubmission submission, Map<String, Submission_Answer__c> answers, Person__c person) {
// Load the TDR
TDR__c tdr = loadTdr(person);
if (tdr == null) {
//Send an email saying that an unregistered person is trying to act a TDR
// Send back the error message
return new String[] { '0', 'User with handset Id ' + submission.imei + ' is not a TDR', 'SUPRESSMSG' };
}
This is the source of the error message.
There is a class the redirects to this method:
private static List<String> additionalProcessing(
SurveySubmission surveySubmission,
Survey__c survey,
Person__c interviewer,
Id intervieweeId
) {
List<String> returnValues = new List<String>();
Map<String, Submission_Answer__c> answers = parseSubmissionToMap(surveySubmission);
// Find the name of the method that this survey hooks into to do its post processing
try {
if (survey.Post_Processing_Method__c.equalsIgnoreCase('None')) {
returnValues.add('0');
returnValues.add('There is no post processing method specified for this survey');
returnValues.add('SUPRESSMSG');
}
else if (survey.Post_Processing_Method__c.equals('CKW_Registration')) {
return CkwRegistration.processCkwRegistration(answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('CKW_Baseline')) {
return CkwRegistration.processCkwBaseline(answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('CKW_Staff_Update')) {
return CkwRegistration.processCkwUpdate(answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('Subcounty_Registration')) {
return CkwRegistration.processSubcounties(answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('TDR_AGENT_VISIT')) {
return TdrHelpers.processAgentVisitSurvey(surveySubmission, answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('UDOM_RAIN_GUAGE')) {
return UDoMSurveyProcessing.processDailyRainGauge(surveySubmission, answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('UDOM_RAIN_GUAGE_REG')) {
return UDoMSurveyProcessing.registerRainGauge(surveySubmission, answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('MTN_CHANNELS')) {
return MtnChannelsHelpers.processChannelsFFPSSurvey(surveySubmission, answers, interviewer);
}
else if (survey.Post_Processing_Method__c.equals('FHI_GROUP_REGISTRATION')) {
return FHISurveysHelpers.processGroupRegistration(surveySubmission, answers, interviewer, survey.Survey_Name__c);
}
else if (survey.Post_Processing_Method__c.equals('FHI_HOUSEHOLD_REGISTRATION')) {
return FHISurveysHelpers.processHouseholdRegistration(surveySubmission, answers, interviewer, survey.Survey_Name__c);
}
// else if (survey.Post_Processing_Method__c.equals('Colombia_Farmer_Registration')) {
// return ColombiaFarmerRegistrationPostProcessor.processSubmission(surveySubmission, answers, interviewer);
// }
else if (survey.Post_Processing_Method__c.equals('FIELD_OFFICER_SUPPORT')) {
return FieldOfficeHelpers.processFoSurvey(surveySubmission, answers, interviewer);
}
// else if (survey.Post_Processing_Method__c.equals('DATA_VALIDATOR_SPOT_CHECK')) {
// return DataValidatorHelpers.processSpotCheck(surveySubmission, answers, interviewer);
// }
// else if (survey.Post_Processing_Method__c.equals('DATA_VALIDATOR_BACK_CHECK')) {
// return DataValidatorHelpers.processBackCheck(surveySubmission, answers, interviewer);
// }
else if (survey.Post_Processing_Method__c.equals('EQUIPMENT_TRACKING')) {
return EquipmentTrackingHelpers.processFieldOfficerSubmission(surveySubmission, answers, interviewer);
}
}
catch (Exception e) {
returnValues.add('0');
returnValues.add(e.getMessage());
returnValues.add('An error occured. Please contact support');
}
return returnValues;
}
which I think is fine...
Please help coz I do not seem to see any problem
Thank you. I hope the code provide is enough.

Usually when I run across that error my first instinct is to look for any queries. In APEX when you return a null value (expected or not) into a single item such as Person__c person = [query that returns objects}; that error is thrown.
The SOLUTION is to ensure data gets returned into a concrete SObject such as...
List<Person__c> persons = [Here is a query or method call];
Then you would check the list with persons.size() This obeys salesforce's Bulkify everything approach they enforce as well as a more robust backend.
Sorry I couldn't provide more support, the error wasn't very evident in your code samples without a line number or debug log.
Good Luck!

Be aware: This error can also appear if you are trying to reference an uninstantiated property of a class.
Example: If you declare a List property of a class, but never instantiate it, and then attempt to add to that list, you will get this error.

Related

Updating an entry in PersistentVector not working NEAR Protocol

I'm trying to update the status of a job object. I get the "success" message return but the value is not updating. Do I miss something?
#nearBindgen
export class Contract {
private jobs: PersistentVector<Job> = new PersistentVector<Job>('jobs');
......
#mutateState()
cancelJob(jobTitle: string): string {
for (let i = 0; i < this.jobs.length; i++) {
if (this.jobs[i].title == jobTitle) {
this.jobs[i].status = "Cancelled";
return "success"
}
}
return "not found";
}
And I'm calling it like that:
near call apptwo.msaudi.testnet cancelJob '{\"jobTitle\":\"title2\"}' --account-id=msaudi.testnet
It’s not enough to update entry when you fetch it. You need to update the storage on the contract as well. Write it back in so to speak.
This isn’t enough
this.jobs[i].status = "Cancelled";
You need to add it back in:
if (this.jobs[i].title == jobTitle) {
const job: Job = this.jobs[i]; // Need an intermediate object in memory
job.status = "Cancelled";
this.jobs.replace(i, job); // Update storage with the new job.
return "success"
}

Removing From ArrayList, In Loop Based On It's Size, But Breaking After Remove Still Gives OutOfBounds

Alright so I remove an object from an array list, then break, but I still get OutOfBounds, I'm kinda confused, could someone help me, I've tried to isolate the problem, but I still can't figure it out.
Here is the error I get:
Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at GameFunctions.closestTarget(GameFunctions.java:37)
at GameFunctions.act(GameFunctions.java:147)
at GamePanel$1.run(GamePanel.java:50)
Here are the two methods causing me problems:
public void act(ArrayList<Germs> g, ArrayList<WhiteBloodCell> p, String actor)
{
if(actor.equals("Germs"))
{
for(int i=0;i<g.size();i++)
{
if(g.get(i) instanceof SPneumoniae)
{
g.get(i).move();
g.get(i).testBounds();
if(checkSize(g, i))
{
System.out.println("broken");
break;
}
}
}
}
else if(actor.equals("WhiteBloodCells"))
{
for(int i=0;i<p.size();i++)
{
p.get(i).setTarget(closestTarget(g, p.get(i)));
p.get(i).move();
}
}
}
And here is the method called that's removing the object:
public boolean checkSize(ArrayList<Germs> g, int i)
{
if(g.get(i).getRadius() > 30)
{
g.get(i).setRadius(30);
}
else if(g.get(i).getRadius() <= 0)
{
g.remove(i);
return true;
}
return false;
}
It looks like the error is due to there being nothing in the ArrayList of g.
Check out this area of your code:
else if(actor.equals("WhiteBloodCells"))
{
for(int i=0;i<p.size();i++)
{
p.get(i).setTarget(closestTarget(g, p.get(i)));
p.get(i).move();
}
}
See if that gives you any leads.
Edit -- The bug IS coming from the closestTarget function based on the exceptions listed.

Get error for using Type object in function

I have a function to return Type Object in the class. It is work on webpage, but not windows phone application. The error is "Expected class, delegate, enum, interface or struct". Would anyone tell me how to solve it. Thanks.
There is my code:
public static object GetData(Uri relativeUri)
{
return GetData<object>(relativeUri);
}
public static T GetData<T>(Uri relativeUri)
{
var request = CreateRequest(relativeUri);
HttpWebResponse r;
//return Deserializer<T>(request.GetResponse().GetResponseStream());
try
{
r = (HttpWebResponse)request.GetResponse();
return Deserializer<T>(r.GetResponseStream());
}
catch (WebException webex)
{
HttpWebResponse webResp = (HttpWebResponse)webex.Response;
setSessionError(webResp.GetResponseStream());
}
return Deserializer<T>(request.GetResponse().GetResponseStream());
}
I found it what is wrong on my code. I have extra close bracket that put the function out of the class.

IE & Ajax / XPath

I've read countless threads and tried implementing many different suggestions, but haven't had any luck.
first:
function ajaxRequest() {
try {
var request = new XMLHttpRequest();
}
catch(e1) {
try {
var request = new ActiveXObject("Msxml2.HTMLHTTP");
}
catch(e2) {
try {
var request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e3) {
var request = false;
}
}
}
return request;
}
It looks like IE is successfully using XMLHttpRequest. As far as I can tell, it's loading the XML fine, but Xpath is another story:
function XMLPath(doc, path) {
try {
return doc.evaluate(path, doc, null, XPathResult.STRING_TYPE, null).stringValue;
} catch (e) {
try {
doc.setProperty("SelectionLanguage", "XPath");
return doc.selectNodes(path);
}
catch(e2) {
alert(e2);
}
}
}
Basically, what must I change in my catch statement to make it work with IE? What's also interesting is that it never alerts an e2 error, meaning it's not actually throwing an error. Totally confused.
Thanks.
Try return doc.selectSingleNode(path).text; for IE, that is the closest you can get for accessing the string value of the node found by your path.

refactor dilemma

I want to extract the guard statement from the following method
private void CreateProxy()
{
//extract the following guard statement.
Host selected = this.comboBox1.SelectedItem as Host;
if (selected == null)
{
return;
}
this.SearchProxy = ServiceProxy.ProxyFactory.CreateSearchProxy(GetSelectedIP().ToString());
this.StreamProxy = ServiceProxy.ProxyFactory.CreatePlayerProxy(GetSelectedIP().ToString());
}
//extracted guard method
public bool IsHostSelected()
{
Host selected = this.comboBox1.SelectedItem as Host;
if (selected == null)
{
return false;
}
return true;
}
see? now i have to add return value for the extracted method, is this kinda ugly?
any better solution to avoid adding the return value for the extracted method?
I don't see the big deal. First, I would rewrite it as:
static bool SelectedItemIsHost(ComboBox box) {
return box.SelectedItem is Host;
}
Note the rename, the ComboBox as a parameter, and the body change.
Now, this makes your code read more clearly:
void CreateProxy() {
if(SelectedItemIsHost(this.comboBox1)) {
this.SearchProxy = ServiceProxy.ProxyFactory.CreateSearchProxy(GetSelectedIP().ToString());
this.StreamProxy = ServiceProxy.ProxyFactory.CreatePlayerProxy(GetSelectedIP().ToString());
}
}
So now it reads "if the selected item is a Host then do stuff."
Now, this goes way beyond your question, but this looks like a big coupling of UI logic and domain logic. You might want to reconsider a decoupling there.
any better solution to avoid adding the return value for the extracted method?
Yes:
//extracted guard method
public bool IsHostSelected()
{
Host selected = this.comboBox1.SelectedItem as Host;
return selected != null;
}

Resources