I got error NullPointerException in Java.  I am just using JSONParser  String test is   {     "processGroupRevision": {         "clientId":"f98f0e63-0164-1000-6c10-442b4b1fbe8f",         "version":1         },         "variableRegistry":{             "variables": [{                 "variable": {                     "name":"123123123",                     "value":"12322",                     "pr": "..."                  }             }]         } }   And here is the main Code  String test = sb.toString(); System.out.println(test);  JSONParser jsonParser = new JSONParser(); JSONObject jsonObj = (JSONObject) jsonParser.parse(test); JSONArray jsonArray = (JSONArray) jsonObj.get("variable");  System.out.println("==================");  for (int i=0; i&lt;jsonArray.size(); i++) {     JSONObject tempObj = (JSONObject) jsonArray.get(i);     System.out.println(""+(i+1)+" key : " + tempObj.get("name"));     System.out.println(""+(i+1)+" value : " + tempObj.get("value")); }   How can I fix this problem?  Is it in the For loop ?
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
29851
I have an error that seems common on the web,  Though i cant find a definite answer that applies to my case:  I have the following Apex code:  public with sharing class templicenseemail {      private ApexPages.standardController standardController;       public Trainee__c trainee { get; set; }     public templicenseemail(ApexPages.StandardController controller) {         this.standardController = standardController;     }      public PageReference doSomething()     {         trainee  = [SELECT Email__c,First_Name__c,Institution__c,Last_Name__c FROM Trainee__c                  WHERE Id = :ApexPages.currentPage().getParameters().get('id')];                  String whatIs = trainee.Volume_Serial_Number__c;                 integer strlen = whatIs.length();                  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, trainee.Email__c  ));         return null;      }     }   And the following test case:  @isTest(seealldata=false)      private class Send_noti_emailsTestClass5 {          static testMethod void validateSend_noti_emails5() {              templicenseemail  MyTestcase = new templicenseemail();              // code here in the Middle              MyTestcase.doSomething();          }     }   I'm getting the following error:  Error: Compile Error: Constructor not defined: [templicenseemail].&lt;Constructor&gt;(SOBJECT:Lead) at line:      templicenseemail  MyTestcase = new templicenseemail();   Does anyone know why?
17519
I have a string containing the , and I need to convert it to a Java Date object.  String date = "1081157732"; DateFormat df = new SimpleDateFormat(""); // This line try {   Date expiry = df.parse(date);  } catch (ParseException ex) {   ex.getStackTrace(); }   The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat().
3046
Assuming I have an ArrayList  ArrayList&lt;MyClass&gt; myList;   And I want to call toArray, is there a performance reason to use  MyClass[] arr = myList.toArray(new MyClass[myList.size()]);   over  MyClass[] arr = myList.toArray(new MyClass[0]);   ?  I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.  Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...
77222
I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.  I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine Update: the caller I have in mind is not another JVM; thanks @Dave Ray  My implementation considerations are typical    performance ease of implementation and maintenance (simplicity?) reliability flexibility (i.e. can I call from a remote machine, etc.)   Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?  (Stuff people have actually done and can provide real-life feedback on would be great!)
18236
Steps to Reproduce   Tap faster on the code. or Tap once on a huge code.   but happens only when  setupForGeneric() is called, might be a bug related to   private void setupForCode()   { String str = getIntent().getStringExtra("com.stackexchange.marvin:code_block"); PrettyWebView localPrettyWebView = (PrettyWebView)findViewById(R.id.code); localPrettyWebView.setPostBody("&lt;pre&gt;&lt;code&gt;" + TextUtils.htmlEncode(str) + "&lt;/pre&gt;&lt;/code&gt;", false); localPrettyWebView.setBackgroundColor("#eeeeee"); }  private void setupForGeneric() { String str = getIntent().getStringExtra("com.stackexchange.marvin:web_url"); PrettyWebView localPrettyWebView = (PrettyWebView)findViewById(R.id.code); localPrettyWebView.getSettings().setBuiltInZoomControls(true); localPrettyWebView.getSettings().setLoadWithOverviewMode(true); localPrettyWebView.getSettings().setUseWideViewPort(true); localPrettyWebView.loadUrl(str); localPrettyWebView.setBackgroundColor("#eeeeee"); }   Log  09-05 03:54:30.312: E/AndroidRuntime(26264): FATAL EXCEPTION: WebViewCoreThread  09-05 03:09:39.522: E/Crittercism(18318): java.lang.NullPointerException: [v0.1.22]  09-05 03:09:39.522: E/Crittercism(18318):   at android.content.ComponentName.&lt;init&gt;(ComponentName.java:75) 09-05 03:09:39.522: E/Crittercism(18318):   at android.content.Intent.&lt;init&gt;(Intent.java:3156) 09-05 03:09:39.522: E/Crittercism(18318):   at com.stackexchange.marvin.ui.ViewPopupActivity.showCode(ViewPopupActivity.java:25) 09-05 03:09:39.522: E/Crittercism(18318):   at com.stackexchange.marvin.ui.question.QuestionFragment$1.onCodeClicked(QuestionFragment.java:67) 09-05 03:09:39.522: E/Crittercism(18318):   at com.stackexchange.marvin.ui.common.PrettyWebView$WebAppInterface.codeClicked(PrettyWebView.java:197) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore.nativeTouchUp(Native Method) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore.nativeTouchUp(Native Method) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore.access$4000(WebViewCore.java:59) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:1449) 09-05 03:09:39.522: E/Crittercism(18318):   at android.os.Handler.dispatchMessage(Handler.java:99) 09-05 03:09:39.522: E/Crittercism(18318):   at android.os.Looper.loop(Looper.java:137) 09-05 03:09:39.522: E/Crittercism(18318):   at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:790) 09-05 03:09:39.522: E/Crittercism(18318):   at java.lang.Thread.run(Thread.java:856)
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
13711
I am trying to install a Java application on my Linux machine (Slackware).   I have received the following error, and I do not understand it.   Could you advise me how to approach the problem? Thank you.  Here is what I get: (I see that some X11 DISPLAY variable needs to be set, but what value should I give it and how?)  ~$ java -jar gate-5.0-beta1-build3048-installer.jar - ERROR -  java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. at java.awt.GraphicsEnvironment.checkHeadless(Graphic sEnvironment.java:159) at java.awt.Window.&lt;init&gt;(Window.java:407) at java.awt.Frame.&lt;init&gt;(Frame.java:402) at net.sourceforge.mlf.metouia.borders.MetouiaDotsBuf fer.&lt;init&gt;(MetouiaDotsBuffer.java:105) at net.sourceforge.mlf.metouia.borders.MetouiaDots.&lt;i nit&gt;(MetouiaDots.java:66) at net.sourceforge.mlf.metouia.borders.MetouiaToolBar Border.&lt;init&gt;(MetouiaToolBarBorder.java:49) at net.sourceforge.mlf.metouia.MetouiaLookAndFeel.ini tComponentDefaults(MetouiaLookAndFeel.java:241) at javax.swing.plaf.basic.BasicLookAndFeel.getDefault s(BasicLookAndFeel.java:130) at javax.swing.plaf.metal.MetalLookAndFeel.getDefault s(MetalLookAndFeel.java:1591) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:537) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:581) at com.izforge.izpack.installer.GUIInstaller.loadLook AndFeel(GUIInstaller.java:373) at com.izforge.izpack.installer.GUIInstaller.&lt;init&gt;(G UIInstaller.java:116) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Construc tor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:30 at com.izforge.izpack.installer.Installer.main(Instal ler.java:62)
74579
I am writing this java program to find all the prime numbers up to num using the Sieve of Eratosthenes, but when I try to compile, it says I can't use a long var as an array index, and it expects an int var in its place. But I'll be working with large numbers, so I can't use int. What can I do?  import java.util.*; import java.lang.*;  public class t3{     public static void main(String[] args){         long num = 100;          //declaring list and filling it with numbers         ArrayList&lt;Long&gt; numlist = new ArrayList&lt;Long&gt;();         for(long x=2 ; x&lt;num ; x++){             numlist.add(new Long(x));         }          //sieve or eratosthenes         for(long x=0 ; x&lt;Math.sqrt(num) ; x++){             for(long y=x+1 ; y&lt;numlist.size() ; y++){                 if(numlist[y]%numlist[x] == 0){                     numlist.remove(y);                 }             }         }          //print list         for(Object item : numlist){             System.out.println((Long)item);         }     } }
74793
I have written a method which I will call in a Trigger.While trying to save this code as Apex class, I am getting the error " Error: Compile Error: Loop variable must be of type SObject at line 7 column 13"   My code goes as below ,appreciate any help, thanks  public class LeadBefore {     public static void UpdateChapterEmailAddress (){          set&lt;Id&gt; JDRFLocationId = new set&lt;Id&gt;();         List&lt;Lead&gt; vLstLead = new List&lt;Lead&gt;();           for(Lead vLead:trigger.new)         {             if(vLead.JDRF_Location__c != null)             {                 JDRFLocationId.add(vLead.JDRF_Location__c);                 vLstLead.add(vLead);             }         }         Map&lt;Id, JDRF_Location__c&gt; vMapIdJDRFLocat = new Map&lt;Id, JDRF_Location__c&gt;([Select Id, Name, General_Email_Address__c from JDRF_Location__c where Id In: JDRFLocationId]);         for(Lead vLead: vLstLead)         {             if(vMapIdJDRFLocat.containsKey(vLead.JDRF_Location__c))             {                 vLead.Chapter_Email_Address__c = vMapIdJDRFLocat.get(vLead.JDRF_Location__c).General_Email_Address__c;             }         }     } }
89206
I am getting error:     The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal   ...while trying to pass variable as parameter to JSON_QUERY function. Please help me to resolve it.  DECLARE @cnt INT = 1; DECLARE @cnt_total INT = 1; DECLARE @json NVARCHAR(MAX); DECLARE @json1 NVARCHAR(MAX); declare @str  VARCHAR(200);  WHILE @cnt &lt;= 10 BEGIN     set @str = '$.Seasons[0].Products['+convert(varchar,@cnt)+'].ProductChannels';     set @str = char(39) +@str+ char(39);     PRINT @STR     select @json = json_query(jfile,@STR) from Import.tstjson; --MORE CODE         SET @cnt = @cnt + 1; END   Sample data:  {   "Seasons": [     {       "Season": "12321231",       "Products": [         {           "ProductId": "211",           "ProductChannels": [             {               "ChannelId": 1,               "WeekQuantities": []             }           ],           "ccc": 3,           "Tttt": 4         }       ]     }   ] }
102259
I need to search a string in the string array. I dont want to use any for looping in it  string [] arr = {"One","Two","Three"};  string theString = "One"   I need to check whether theString variable is present in arr.
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
114531
I need to serialize a list of SObject without omission null values. This string I need for a later usage in JavaScript. Structure is crucial, because I need to construct a table out of it. The structure is very dynamic. Different SObjects may lead to different fields and therefore different columns. Missing values will corrupt all the output and are unacceptable.  As it stands, in current versions JSON.serialize() will not output null values. There are already some questions about this raised, but either the answers there are incorrect or I'm doing something wrong to apply them right:       As far as I understand, Apex version 28.0 and newer should have no null values and version 27.0 and older should have them. But I can't make it work. There was an issue that the JSON.serialized() was not versioned right but as to  it should be working now.   So I've created this helper-class:  public class elfApi27 {      public static string dump0(Object o) {         return system.JSON.serializePretty(o);      } }   Setting the version like this in the xml  &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ApexClass xmlns="http://soap.sforce.com/2006/04/metadata"&gt;     &lt;apiVersion&gt;27.0&lt;/apiVersion&gt;     &lt;status&gt;Active&lt;/status&gt; &lt;/ApexClass&gt;   tested it via execute anonymous like this (consider xl.log as system.debug)  Account a = new Account(name='test'); xt.log( elfApi27.dump0(a) );   I have tried all the versions from 32.0 down to 24.0 but the output stays rock-solid like this:  DB Callout Profile Code Escape   32.0 APEX_CODE,WARN;APEX_PROFILING,WARN;CALLOUT,WARN;DB,WARN;SYSTEM,WARN 19:09:02.119 (119823175)|EXECUTION_STARTED 19:09:02.119 (119833395)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex 19:09:02.132 (132802344)|USER_DEBUG|[230]|WARN|"{    "attributes" : {       "type" : "Account"    },    "Name" : "test" }" 19:09:02.132 (132848199)|CODE_UNIT_FINISHED|execute_anonymous_apex 19:09:02.134 (134336841)|EXECUTION_FINISHED    Am I misinterpreting the answers?  Is there any way to have a full verbose serialization of objects?
24499
I'm trying to parse some JSON using the JSon.Net library.  The documentation seems a little sparse and I'm confused as to how to accomplish what I need.  Here is the format for the JSON I need to parse through.  {     "displayFieldName" : "OBJECT_NAME",      "fieldAliases" : {         "OBJECT_NAME" : "OBJECT_NAME",          "OBJECT_TYPE" : "OBJECT_TYPE"     },      "positionType" : "point",      "reference" : {         "id" : 1111     },      "objects" : [ {         "attributes" : {             "OBJECT_NAME" : "test name",              "OBJECT_TYPE" : "test type"         },          "position" : {             "x" : 5,              "y" : 7         }     } ] }   The only data I really need from this is the stuff in the objects array.  Is it possible for me to parse through that with something like the JSonTextReader and just pull out the things I want, like OBJECT_TYPE and the x and y position?  I can't seem to get JSonTextReader to work the way I want it to and I find little to no examples of usage for it.   It seems like serializing first then using LINQ with my object would be ideal and every example I find discusses serializing the JSON first, but I'm not sure how I would build an object for this structure.  Particularly the objects array which would need to be something like a list of Pairs of attribute and position objects.  I have no idea how I would code my object so JSon.Net would know how to serialize that.  I thought I could write my own simple parser to just pull out everything I need into an attributes object that I created, but I'm having little luck.    Hopefully this all makes sense, any ideas?
101821
while making a call from php i am getting the error      Attempt to de-reference a null object Class.Demo.Insert:   What is problem in my webservice?  global class Ctest{     global class RequestClass{         webservice String accName;     }      webservice static void   cInsert(RequestClass req){         Account a1 = new Account();         a1.Name = req.accName;         insert a1;     } }   And Our Php Code Is  require_once('salesforceAPI/soapclient/SforceEnterpriseClient.php'); require_once('salesforceAPI/soapclient/SforceHeaderOptions.php');  $sfdc = new SforceEnterpriseClient(); $SoapClient = $sfdc-&gt;createConnection('enterprise.wsdl.xml');  $loginResult = false;  $loginResult = $sfdc-&gt;login(USER, PASSWORD . SECURITY_KEY);  $parsedURL = parse_url($sfdc-&gt;getLocation()); define("_SFDC_SERVER_", substr($parsedURL['host'], 0, strpos($parsedURL['host'], '.'))); define("_WS_NAME_", 'salesforceAPI/Ctest'); define("_WS_WSDL_", _WS_NAME_ . '.xml'); define("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_); define("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);  $client = new SoapClient(_WS_WSDL_); $sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" =&gt; $sfdc-&gt;getSessionId())); $client-&gt;__setSoapHeaders(array($sforce_header));  $method = $client-&gt;__getFunctions();  $wsParams = array('accName' =&gt; 'XXXXXXX');  $client-&gt;cInsert($wsParams)
93419
I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:  website/Admin/action   however if I miss spell the controller name I get the error below:  Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: key  There error occurs on this line:  Controller controller = ObjectFactory.GetInstance(controllerType) as Controller;   Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just goto a 404 page??  Cheers in advance