获取XML并解析它时出错

时间:2017-10-21 12:44:14

标签: android xml

public String getMetaData() {
    String errors = "";
    try {
        URL url = new URL("http://in2streaming.com:9999/stats?sid=1.xml");
        URLConnection conn = url.openConnection();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        // Error Here:
        Document doc = db.parse(conn.getInputStream().toString());

        // get the root node
        NodeList nodeList = doc.getElementsByTagName("SHOUTCASTSERVER");
        Node node=nodeList.item(0);
        // the  node has three child nodes
        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            Node temp=node.getChildNodes().item(i);
            if(temp.getNodeName().equalsIgnoreCase("SONGTITLE")){
                return temp.getTextContent();
            }
        }
        return "Couldn't reach XML";
    }
    catch (Exception e) {
        return "Exception ";
    }
}

通过Runnable调用此函数,获得异常android.os.NetworkOnMainThreadException 我可能会将链接更改为http://in2streaming.com:9999/7.html并使用HTMl解析器

// Refresh meta data
private final Runnable refresh_meta = new Runnable() {
    @Override
    public void run() {
        Toast.makeText(m_context, getMetaData(), Toast.LENGTH_SHORT).show();
        m_handler.postDelayed(this, 5000);
    }
};

2 个答案:

答案 0 :(得分:2)

对于NetworkOnMainThreadException(您也可以使用AsyncTask):

Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, getMetaData(), Toast.LENGTH_SHORT).show();
            }
        });

如果你想每5秒安排一次。

您可以使用ScheduledExecutorService

ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();

        worker.scheduleAtFixedRate(refresh_meta,
                1,  //initial delay
                5, //run every 5 seconds
                TimeUnit.SECONDS);

将您的Runnable更新为

private Runnable refresh_meta = new Runnable() {
        @Override
        public void run() {
            final String text = getMetaData();

            runOnUiThread(new Runnable() {
                              @Override
                              public void run() {
                                  Toast.makeText(m_context, text, Toast.LENGTH_SHORT).show();
                              }
                          }
            );


        }
    };

此外,

Document doc = db.parse(conn.getInputStream().toString());更改为

Document doc = db.parse(conn.getInputStream());

答案 1 :(得分:1)

首先是一些评论:

a)不要像你在这里做的那样消除例外:

catch (Exception e) {
    return "Exception ";
}

这样你永远不会知道抛出的异常是什么。最好记录/打印异常的堆栈跟踪,例如:

catch (Exception e) {
    Log.e("TAG", "Error", e);
    return "Exception";
}

b)conn.getInputStream().toString()没有按照您的预期执行操作(将InputStream转换为String)。 DocumentBuilder的{​​{3}}方法需要InputStream作为参数,无需将其转换为String

在这里考虑以上因素是你的方法:

public String getMetaData() {
    String errors = "";
    try {
        URL url = new URL("http://in2streaming.com:9999/stats?sid=1.xml");
        URLConnection conn = url.openConnection();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        // Error Here:
        Document doc = db.parse(conn.getInputStream());

        // get the root node
        NodeList nodeList = doc.getElementsByTagName("SHOUTCASTSERVER");
        Node node=nodeList.item(0);
        // the  node has three child nodes
        for (int i = 0; i < node.getChildNodes().getLength(); i++) {
            Node temp=node.getChildNodes().item(i);
            if(temp.getNodeName().equalsIgnoreCase("SONGTITLE")){
                return temp.getTextContent();
            }
        }
        return "Couldn't reach XML";
    }
    catch (Exception e) {
        Log.e("TAG", "Error in getMetaData()", e);
        return "Exception ";
    }
}

再次尝试运行您的应用程序,如果此方法出现错误,它将打印在您的logcat中,并显示消息“getMetaData()中的错误”。通过错误相应地更新您的问题,让其他成员帮助您。