Results 1 to 2 of 2
  1. #1
    Max123 is offline Member
    Join Date
    May 2014
    Posts
    1
    Rep Power
    0

    Unhappy How to avoid NullPointerException?

    Hi! Since i am very new to java, i need a bit of your help.
    I have been playing around with my code, but still have no idea how to avoid NullPointerexception...

    So my program's point is simple, use Jsoup to scrape html of certain webpage, then i search the things i want and print them out.
    Problem is, when scraped html doesnt contain even 1 thing on my search list, i get NullPointerException... i understand why, but i have no idea how to work around it


    Hope you guys can suggest me some methods, heres part of my code:

    Java Code:
      
                    //Things i need to search from html
                    String[] MySearchArray = new String[]{"138","146","474"};
                            //Search things contained in MySearchArray and print them out
    			for (String Ml : MySearchArray) {
    				Element flights = doc.select(String.format("tr:contains(%s)", Ml)).first();
    			        Elements flights2 = flights.select("td");			
           	                        System.out.println(flights2.get(4).text() + " " + flights2.get(0).text()+ " " + flights2.get(3).text());			 
    			}

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

    Default Re: How to avoid NullPointerException?

    how to avoid NullPointerexception...
    If a method can return a null value, test the value for null before using it.
    Java Code:
    Object obj = method();  // can return null
    if(obj == null) {            // test the value returned
      // handle null value
    } else {
      // handle non-null
    }
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. How to avoid many if else conditions
    By Addymails in forum New To Java
    Replies: 9
    Last Post: 03-22-2012, 01:39 PM
  2. How to avoid this problem...
    By pbaudru in forum AWT / Swing
    Replies: 6
    Last Post: 01-21-2010, 02:20 PM
  3. How to avoid focus()..?
    By ehochedez in forum NetBeans
    Replies: 9
    Last Post: 08-27-2009, 12:32 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •