I am trying to get an XML file from a url using HTTP Get method in Android. When I enter the url in my browser I get the XML file. However when I try and use HttpURLConnection in Android, the input stream is always null. I am trying to figure out the problem but in vain. I would like some help in understanding the problem.
Here are my codes:
XML File
<?xml version="1.0" encoding="UTF-8"?>
<item>
<log>27.1823000000</log>
<lat>88.5012200000</lat>
</item>
Async Task
private class GetOnlineData extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... voids){
String latlog=null;
// Accessing link to obtain XML file
try{
URL url = new URL(link);
HttpURLConnection htc = (HttpURLConnection) url.openConnection();
inputStream = htc.getInputStream();
}catch(Exception e){}
// Parsing XML data from input stream
if(inputStream!=null){
try {
DocumentBuilderFactory xmlparser = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = xmlparser.newDocumentBuilder();
Document dc = dBuilder.parse(inputStream);
Element ele = dc.getDocumentElement();
ele.normalize();
NodeList nodeList = dc.getElementsByTagName("item");
for (int i=0; i<nodeList.getLength(); i++){
Node node = nodeList.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE){
Element ele2 = (Element) node;
latlog = "Longitude: "+getValue("log",ele2)+"\n";
latlog += "Latitude: "+getValue("lat",ele2);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
return latlog;
}
@Override
protected void onPostExecute(String latlog){
if(inputStream==null) {
Toast.makeText(getApplicationContext(), "Didn't Work", Toast.LENGTH_SHORT).show();
} else {
textView.setText(latlog);
}
}
}
getValue(String, Element)
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
– dannyBoy Dec 29 '16 at 17:02