尝试使用DOM解析XML文件时获取NullPointerException

时间:2014-10-28 20:57:31

标签: java android xml

我已经挣扎了3天左右,最后我决定冒风险问你们。问题是,我从标题中获得了NullPointerException。使用调试器,我发现了我的问题的根源,所以我确切地知道是什么原因导致nullpointer:它的变量" doc"类型为Document,您可以在下面的代码中找到它。对不起,有太多的话,这是代码

这是我的班级DomXmlParser的代码

public class DomXmlParser {
    Document doc;
    String urlLink;
    InputStream is;

    public DomXmlParser(String url){
        this.urlLink = url;
    }

    public Document getDoc(){
        return doc;
    }
    public void parseXML(InputStream is) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(is);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void getXML(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    URL url = new URL(urlLink);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setReadTimeout(15000);
                    conn.setConnectTimeout(15000);
                    conn.setDoInput(true);
                    conn.connect();
                    is = conn.getInputStream();
                    Log.d("InputStreamContents", is.toString());
                    parseXML(is);
                    is.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
}

因此,在MainActivity中,我调用getXml()方法,然后调用getDoc()。

public void parseDom(){
    DomXmlParser parser = new DomXmlParser(xmlUrl);
    parser.getXML();
    doc = parser.getDoc();
    NodeList list = doc.getElementsByTagName("item");
    for (int i = 0; i < list.getLength(); i++){
        Node item = list.item(i);
        if (item.getNodeType()==Node.ELEMENT_NODE){
            Element data = (Element) item;
            NodeList dataList = data.getChildNodes();
            for (int j = 0; j < dataList.getLength(); i++){
                Node p = dataList.item(j);
                if (p.getNodeType()==Node.ELEMENT_NODE){
                    Element title = (Element) p;
                    Element description = (Element) p;
                    FeedItem fi = new FeedItem();
                    fi.setName(title.getTextContent());
                    fi.setStatus(description.getTextContent());
                    feedItems.add(fi);
                }
            }
        }
    }
}

我调试了我的应用程序,看起来getDoc()方法返回null。它也说行

NodeList list = doc.getElementsByTagName("item");

返回null。因此,DomXmlParser类的Document doc变量为null。我确信,InputStream不是null,当我尝试通过XmlPullParser解析XML时,一切正常,因此XML文件或链接都可以。希望你能帮助我们,因为我和谷歌都不知道该做什么。

更新:正如下面的答案中所建议的那样,我删除了Thread,并且刚刚创建了一个在MainActivity中扩展了AsyncTask的类,所以现在我没有那个NullPointer,但我有另一个问题:Out 144字节分配的内存。我不知道该怎么做。

日志

10-29 00:17:13.139    3258-3258/com.motoharu.cleaningapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.motoharu.cleaningapp.HomeFragment.parseDom(HomeFragment.java:151)
            at com.motoharu.cleaningapp.HomeFragment.initControls(HomeFragment.java:78)
            at com.motoharu.cleaningapp.HomeFragment.onStart(HomeFragment.java:70)
            at android.support.v4.app.Fragment.performStart(Fragment.java:1528)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:972)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
            at android.view.View.measure(View.java:16030)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:314)
            at android.view.View.measure(View.java:16030)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
            at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)
            at android.view.View.measure(View.java:16030)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:314)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2196)
            at android.view.View.measure(View.java:16030)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1915)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1290)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1009)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5508)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
            at android.view.Choreographer.doCallbacks(Choreographer.java:562)
            at android.view.Choreographer.doFrame(Choreographer.java:532)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:5225)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
            at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

问题是因为getXML正在产生一个新线程,该线程构造Document引用的doc对象。因此,在调用parser.getXML()之后,代码尝试使用doc方法访问getDoc()变量,但该变量仍未由该线程初始化。

解决方案是等待线程完成。这可以简单地使用join来完成。例如,您可以在调用Thread方法时创建新的getXML,而不是在方法本身内创建它。

public void getXML(){       
    try {
       URL url = new URL(urlLink);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       conn.setRequestMethod("POST");
       conn.setReadTimeout(15000);
       conn.setConnectTimeout(15000);
       conn.setDoInput(true);
       conn.connect();
       is = conn.getInputStream();
       Log.d("InputStreamContents", is.toString());
       parseXML(is);
       is.close();
   }catch(Exception e){
       e.printStackTrace();
   }
}

parseDom

final DomXmlParser parser = new DomXmlParser(xmlUrl);

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        parser.getXML();
    }
});
thread.start();
try {
    thread.join();  // wait until above thread finishes
} catch (InterruptedException e) {
    // handle the exception here
}
doc = parser.getDoc();

答案 1 :(得分:1)

嗯,某种答案。至于唯一的答案没有解决我的问题,我继续谷歌搜索并发现一个信息说,最好不使用DOM,而是使用SAX解析器来解析RSS提要,所以我这样做了。但是,最终,我遇到了同样的NullPointer问题,我不知道为什么。一切都是因为我在新线程中获得的数据并没有与Thread之外的数据相互作用 马努蒂爵士说。所以,他的回答解决了我的问题,但这次使用SAX解析器。