开发者

NullPointerException in DOM seletor method

I keep getting this error

NullPointer

08-16 22:55:46.360: ERROR/AndroidRuntime(11047): Caused by: java.lang.NullPointerException
  08-16 22:55:46.360: ERROR/AndroidRuntime(11047):     at com.fttech.htmlParser.releaseInfo.onCreate(releaseInfo.java:62)
08-16 22:55:46.360: ERROR/AndroidRuntime(11047):     at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
08-16 22:55:46.360: ERROR/AndroidRuntime(11047):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)

Its pointing to my Element here

    Element paragraph = overview.select("p").last();

i am using this to retrieve the article

    try {
        doc = Jsoup.connect(url).get();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    if(doc == null){
        Toa开发者_Python百科st.makeText(this, "Couldnt retrieve game info", Toast.LENGTH_SHORT);
    }
    else{

    // Get the overview div
    Element overview = doc.select("div#object-overview").last();


Everytime you look for an element with select("") your calling last() in a chain which assumes it will always find atleast 1 element, in the situation that there is no say "p" in the document, that is when you will encounter a crash.

It's just simple NullPointerExceptions, you need to learn to code defensively:

// If you believe overview could be null
if(overview != null){
    ArrayList<Element> paragraphs = overview.select("p"); // Whatever type select(String) returns
    Element lastParagraph = null;
    if(paragraphs != null){
         lastParagraph = paragraphs.last();
    } else {
     // Deal with not finding "p" (lastParagraph is null in this situation)
    }

   // Continue with lastParagraph 

} else {
  // Deal with overview being null
}

Number 1 Java Error (scroll down)

Also you shouldn't really wrap your code with a catch all Exception, try to catch each exception and deal with them individually.

Lookup the API for your get() method Jsoup get() (eclipse tells you this anyway) It throws IOException, so you should just catch this.

  try {
        doc = Jsoup.connect(url).get();
    } catch (IOException e) {
        Log.e("Tag", "Jsoup get didn't get a document", e);
    } 

Number 5 Java Error (scroll down)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜