I'm getting the "android.os.NetworkOnMainThreadException"
even though I'm not running anything network related in my main thread. How can I fix this?
I actually tried the code inside Eclipse and it worked just fine, but not in Android Studio where I'm developing the app itself.
Testclass.java:
package com.*****.*****;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.View;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.xpath.*;
import javax.xml.namespace.*;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
abstract class Testclass {
public static class NamespaceResolver implements NamespaceContext {
private Document document;
public NamespaceResolver(Document doc) {
document = doc;
}
public String getNamespaceURI(String prefix) {
if (prefix.equals("")) {
return document.lookupNamespaceURI(null);
} else {
return document.lookupNamespaceURI(prefix);
}
}
public String getPrefix(String namespaceURI) {
return document.lookupPrefix(namespaceURI);
}
public Iterator<String> getPrefixes(String namespaceURI) {
return null;
}
}
public static String downloadString(String url) throws Exception {
StringBuilder sb = new StringBuilder();
try (BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "UTF-8"))) {
String line;
while ((line = r.readLine()) != null) {
sb.append(line + "\n");
}
}
return sb.toString();
}
public static Document createDocumentFromString(String xml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
}
static String value;
public static String result() {
try {
String url = "http://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::observations::mareograph::timevaluepair&fmisid=134223&";
String xml = downloadString(url);
Document document = createDocumentFromString(xml);
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceResolver(document));
String time = xpath.evaluate("//wml2:MeasurementTimeseries[@gml:id='obs-obs-1-1-WATLEV']/wml2:point[last()]//wml2:time", document);
value = xpath.evaluate("//wml2:MeasurementTimeseries[@gml:id='obs-obs-1-1-WATLEV']/wml2:point[last()]//wml2:value", document);
System.out.format("time = %s; value = %s\n", time, value);
return value;
} catch (Exception e) {
return "FAIL: " + e.toString();
}
}
}
Output when run in android studio: "null"
and also throws "android.os.NetworkOnMainThreadException"
Output when run in Eclipse: "-97.0"
(correct output)