【发布时间】:2019-09-22 17:48:40
【问题描述】:
我得到"android.os.NetworkOnMainThreadException",即使我没有在我的主线程中运行任何与网络相关的东西。我该如何解决这个问题?
我实际上在 Eclipse 中尝试了代码,它工作得很好,但在我正在开发应用程序的 Android Studio 中却不行。
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();
}
}
}
在 android studio 中运行时的输出:"null" 并抛出 "android.os.NetworkOnMainThreadException"
在 Eclipse 中运行时的输出:"-97.0"(正确输出)
【问题讨论】:
-
那么
downloadString(String url)这个方法在做什么呢? -
@KaranMer 它下载字符串并将其分配给一个名为“sb”的变量。