从android中的url获取XML

时间:2013-05-29 16:05:16

标签: java android android-layout

我是android的新手。我想从网址获取XML。我的申请很简单。 MainActivity有一个按钮,可以导航到下一个屏幕并显示XML数据

以下是我从在线资源获得的示例代码,但它对我不起作用。它什么也没显示。

private class LongOperation extends AsyncTask<String, Void, LinearLayout> {

    @Override
    protected LinearLayout doInBackground(String... string) {
        LinearLayout layout = new LinearLayout(DevicesActivity.this);
        layout.setOrientation(1);
        /** Create a new textview array to display the results */ 
        TextView name[];
        TextView website[];
        TextView category[];
        try {
            URL url = new URL(
                    "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("item");
            /** Assign textview array lenght by arraylist size */
            name = new TextView[nodeList.getLength()];
            website = new TextView[nodeList.getLength()];
            category = new TextView[nodeList.getLength()];
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                name[i] = new TextView(DevicesActivity.this);
                website[i] = new TextView(DevicesActivity.this);
                category[i] = new TextView(DevicesActivity.this);
                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("name");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                name[i].setText("Name = "
                        + ((Node) nameList.item(0)).getNodeValue());
                NodeList websiteList = fstElmnt.getElementsByTagName("website");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                website[i].setText("Website = "
                        + ((Node) websiteList.item(0)).getNodeValue());
                category[i].setText("Website Category = "
                        + websiteElement.getAttribute("category"));
                layout.addView(name[i]);
                layout.addView(website[i]);
                layout.addView(category[i]);
            }
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }
        /** Set the layout view to display */
        return layout;
    }      

    protected void onPostExecute(LinearLayout result) {
        setContentView(result);
        // here you will get the result
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /** Create a new layout to display the view */
     //setContentView(R.layout.activity_devices);
     new LongOperation().execute("");

}
来自LogCat的

日志

05-29 16:00:50.972: I/Choreographer(6780): Skipped 33 frames!  The application may be doing too much work on its main thread.
05-29 16:00:51.122: D/gralloc_goldfish(6780): Emulator without GPU emulation detected.
05-29 16:00:54.252: I/System.out(6780): XML Pasing Excpetion = android.os.NetworkOnMainThreadException
05-29 16:00:55.663: I/Choreographer(6780): Skipped 71 frames!  The application may be doing too much work on its main thread.

更新

05-29 19:55:38.952: E/Trace(7739): error opening trace file: No such file or directory (2)
05-29 19:55:41.022: D/gralloc_goldfish(7739): Emulator without GPU emulation detected.
05-29 19:55:48.472: I/Choreographer(7739): Skipped 31 frames!  The application may be doing too much work on its main thread.
05-29 19:55:49.182: I/Choreographer(7739): Skipped 68 frames!  The application may be doing too much work on its main thread.
05-29 19:55:50.662: I/System.out(7739): XML Pasing Excpetion = java.lang.SecurityException: Permission denied (missing INTERNET permission?)

2 个答案:

答案 0 :(得分:3)

你不能在主线程中进行Http调用,而是使用AsyncTask。

创建一个扩展AsyncTask的内部类,并在doInBackground方法中完成工作

private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        // do your call here
    }      

    @Override
    protected void onPostExecute(String result) {               
        // here you will get the result
    }
}

您可以在onCreate中调用它,如下所示:

new LongOperation().execute("myParams");

答案 1 :(得分:2)

当主线程中运行某些网络操作时,android会返回此异常。你应该尝试asynctask类。其余代码似乎没问题。阅读关于asynctask的文档。希望这有帮助!