Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Need help parsing XML from a URL into an Android Application

I am creating an android app (using android studio) which uses live data from the link: http://transportapi.com/v3/uk/public/journey/from/Ladbroke%20Grove/to/Turnham%20Green.xml?api_key=a0d27caa983732936f45a891ebca6452&app_id=dc5f42ae&region=tfl

The information is in the form of XML, meaning I need to parse it into my application using a DOM parser. However, an error seems to occur when the code gets to this point:

Document doc = db.parse(new InputSource(url.openStream())); My program isn't showing any errors when I run it, it simply throws an error every time it reaches this point on the code. This results in 'not reading' being printed out in the textView (declared as tv1 in the code).

I understand there are lots of questions on here regarding parsing XML from a URL on android, however none of them seem to help my situation! If anyone has any ideas what I have done wrong they would be much appreciated.

try {

    URL url = new URL("http://transportapi.com/v3/uk/public/journey/from/Ladbroke%20Grove/to/Turnham%20Green.xml?api_key=a0d27caa983732936f45a891ebca6452&app_id=dc5f42ae&region=tfl");


    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbFactory.newDocumentBuilder();

    Document doc = db.parse(new InputSource(url.openStream()));
    doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("route");

    for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            tv1.setText(tv1.getText() + "Duration of route " + ": " + getValue("duration", eElement) + "\n");
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
    tv1.setText("not reading");
}



  private static String getValue(String sTag, Element eElement) {
       NodeList nlList =  eElement.getElementsByTagName(sTag).item(0).getChildNodes();
          Node nValue = (Node) nlList.item(0);
          return nValue.getNodeValue();
   }
   }

Comments