I am trying to write a simple RSS Reader. I think i done but I get exception with "null" message. JavaDoc said that it is possible to get this value so it's nothing strange. But how could I find out what is wrong with my code?   and main:   public static void main(String[] args) throws MalformedURLException {     URL url = new URL("http://facet.wp.pl/rss.xml");     Feed feed = new Feed();     RSSParser parser = new RSSParser(url);     parser.RSSFeed();      for(String wejscia : feed.entries){         System.out.println(wejscia);     } }   @EDIT The exception is at RSSParser.RSSFeed(RSSParser.java:28) and i have already know that it's a NullPointerException
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?
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
84120
Does anyone have any idea why the following code sample fails with an XmlException "Data at the root level is invalid. Line 1, position 1."  var body = "&lt;?xml version="1.0" encoding="utf-16"?&gt;&lt;Report&gt; ......" XmlDocument bodyDoc = new XmlDocument();             bodyDoc.LoadXml(body);
8114
I have same exception can please   The previous post issue is resolved.  Exception: :System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out  Visualforce Page   &lt;apex:page controller="Controller" action="{!init}" showHeader="false" sidebar="false"&gt;     &lt;center&gt;         &lt;apex:pageBlock title="Request Listener"&gt;&lt;/apex:pageBlock&gt;               &lt;/center&gt; &lt;/apex:page&gt;   Controller :            PUBLIC with sharing class Controller {        PUBLIC String fromNumber      = ApexPages.currentPage().getParameters().get('From');     PUBLIC String toNumber        = ApexPages.currentPage().getParameters().get('To');     PUBLIC String body            = ApexPages.currentPage().getParameters().get('Body');        PUBLIC PageReference init()     {                    System.debug('From Phone Number :' +fromNumber);         System.debug('To phone NUmber :' + toNumber);         System.debug('Message Body :' + body);          TwilioRestClient Client = TwilioAPI.getDefaultClient();                                                                SYSTEM.DEBUG('FROM AND To  Number is NOT NULL');                      String formattedNumber='+919876543210';                 IF(body != NULL)                 body = body;             ELSE                 body = '';             Case c = NEW Case (Subject = formattedNumber,Description = body,Origin = 'Phone');             INSERT c;                               Map&lt;String,String&gt; params1 = new Map&lt;String,String&gt;             {                'To'   =&gt; fromNumber,                'From' =&gt; '+1908280****',                'Body' =&gt; 'Conformation to customer'             };             TwilioMessage message = client.getAccount().getMessages().create(params1); /* Valid conformation SMS sent to the Customer.*/                                            return null ;     } }   While loin as admin then click preview on visualforce page executed but case is not created.I have checked the the debug log it throw the exception.
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
67536
I have a class with a nullable int? datatype set to serialize as an xml element.  Is there any way to set it up so the xml serializer will not serialize the element if the value is null?    I've tried to add the [System.Xml.Serialization.XmlElement(IsNullable=false)] attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute."  [Serializable] [System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")] public class Score {     private int? iID_m;     ...      /// &lt;summary&gt;     ///      /// &lt;/summary&gt;             public int? ID      {          get          {              return iID_m;          }          set          {              iID_m = value;          }      }      ... }   The above class will serialize to:  &lt;Score xmlns="http://mycomp.com/test/score/v1"&gt;     &lt;ID xsi:nil="true" /&gt; &lt;/Score&gt;   But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like
102393
What would you consider to be the best exception type to throw when an extension method is called on a null instance (where the extension method does not allow it)? Since extension methods are nothing but static methods you could argue that it should be ArgumentNullException, but on the other hand they're used like instance methods so it might be more natural to use the NullReferenceException. Let's take the following example:  public static string ToInvariantString(this IFormattable value, string format) {     return value.ToString(format, CultureInfo.InvariantCulture); }   This way a NullReferenceException will be thrown if the value parameter is null.   The other example would be:  public static string ToInvariantString(this IFormattable value, string format) {     if (value == null) throw new ArgumentNullException("value");     return value.ToString(format, CultureInfo.InvariantCulture); }   EDIT: In some of the answers you have pointed out that an extension methods can be called like a static method and in those cases a null reference exception would be wrong, which is a great point, and actually one of my concerns, not sure why I forgot to mention that in the question in the first place.   Someone also pointed out that it's wrong to throw a NullReferenceException, and yes, it is. That's why I don't throw it, I just let it happen (let the CLR throw it) by not guarding the method.  I think I favor the ArgumentNullException (that's what I've use so far) but I still think there is at least room to argue for an against the NullReferenceException since it seems more natural in most places where the method is going to be used.
43302
I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)  Solution Thanks to , I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - SAXException - or just bad IO - IOException.)  public static org.w3c.dom.Document loadXMLFrom(String xml)     throws org.xml.sax.SAXException, java.io.IOException {     return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes())); }  public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)      throws org.xml.sax.SAXException, java.io.IOException {     javax.xml.parsers.DocumentBuilderFactory factory =         javax.xml.parsers.DocumentBuilderFactory.newInstance();     factory.setNamespaceAware(true);     javax.xml.parsers.DocumentBuilder builder = null;     try {         builder = factory.newDocumentBuilder();     }     catch (javax.xml.parsers.ParserConfigurationException ex) {     }       org.w3c.dom.Document doc = builder.parse(is);     is.close();     return doc; }
47519
Every time a user posts something containing &lt; or &gt; in a page in my web application, I get this exception thrown.  I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.  Trapping the exception and showing     An error has occurred please go back and re-type your entire form again, but this time please do not use &lt;   doesn't seem professional enough to me.  Disabling post validation (validateRequest="false") will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.  Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded. So the .Text property of my text-box will be something &amp; lt; html &amp; gt;  Is there a way I can do this from a handler?
120763
I have to serialize around a million items and I get the following exception when I run my code:  Exception in thread "main" java.lang.OutOfMemoryError: Java heap space     at java.util.Arrays.copyOfRange(Unknown Source)     at java.lang.String.&lt;init&gt;(Unknown Source)     at java.io.BufferedReader.readLine(Unknown Source)     at java.io.BufferedReader.readLine(Unknown Source)     at org.girs.TopicParser.dump(TopicParser.java:23)     at org.girs.TopicParser.main(TopicParser.java:59)   How do I handle this?
77755
&lt;servlet&gt;     &lt;servlet-name&gt;myservlet&lt;/servlet-name&gt;     &lt;servlet-class&gt;workflow.WDispatcher&lt;/servlet-class&gt;     &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt;  &lt;servlet-mapping&gt;     &lt;servlet-name&gt;myservlet&lt;/servlet-name&gt;     &lt;url-pattern&gt;*NEXTEVENT*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt;   Above is the snippet from Tomcat's web.xml. The URL pattern *NEXTEVENT* on start up throws     java.lang.IllegalArgumentException: Invalid &lt;url-pattern> in servlet mapping   It will be greatly appreciated if someone can hint at the error. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
21733
EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)     ? null     : Convert.ToInt32(employeeNumberTextBox.Text),  I often find myself wanting to do things like this (EmployeeNumber is a Nullable&lt;int&gt; as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values).  Unfortunately, the compiler feels that  There is no implicit conversion between 'null' and 'int'  even though both types would be valid in an assignment operation to a nullable int on their own. Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the .Text string if it's not null. As far as I know the only way to do this is to use an if statement and/or assign it in two steps.  In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block... Does anyone know a more elegant solution?
1876
I am trying to make a share on linkedin link on my lightning component of community like this :    &lt;a href="https://www.linkedin.com/shareArticle?mini=true&amp;amp;url=my_url_here;&amp;amp;title="+{!v.SingleBlog.Title__c}+"&amp;amp;summary=sdfsjf"   target="_new" &gt;  Linkedin      &lt;/a&gt;    But When I am saving this its giving me an error :  Getting   Field Integrity Exception :  Failed to save undefined: markup://c:BlogDetail:70,162: ParseError at [row,col]:[71,162] Message: Element type "a" must be followed by either attribute specifications, "&gt;" or "/&gt;".:    I know its because of the variable {!v.SingleBlog.Title__c} whose value I want to append in share url at runtime.   How to put this variable's value in url?
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
107801
I posted the code below to the Sun developers forum since I thought it was erroring (the true error was before this code was even hit).  One of the responses I got said it would not work and to throw it away.  But it is actually working.  It might not be the best code (I am new to Java) but is there something inherently "wrong" with it?   =============  CODE:   private static void ImportFromCsvToAccessTable(String mdbFilePath, String accessTableName  , String csvDirPath , String csvFileName ) throws ClassNotFoundException, SQLException {      Connection msConn = getDestinationConnection(mdbFilePath);     try{          String strSQL = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";         PreparedStatement selectPrepSt = msConn.prepareStatement(strSQL );         boolean result = selectPrepSt.execute();                 System.out.println( "result = " + result );      } catch(Exception e) {         System.out.println(e);     } finally {         msConn.close();     } }
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.