简体   繁体   中英

Get XML from url in android

I'm new to android. I want to get the XML from the url. My application is very simple. The MainActivity has a button that navigates to next screen and display the XML data

The following is the example code that I got from online sources, but it doesn't work for me. It displays nothing.

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("");

}

logs from 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.

updated

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?)

You cannot do an Http call in your main thread, use an AsyncTask instead.

Create an inner class that extends an AsyncTask and do your work inside the doInBackground method

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
    }
}

You can call it in your onCreate like this:

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

android returns this exception when some networking opperation is running in the main thread. you should try asynctask class. the rest of the code seems to be ok. read the documebtation on asynctask. hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM