我得到了"android.os.NetworkOnMainThreadException",尽管我在主线程中没有运行任何相关的网络。我怎么才能解决这个问题?
实际上,我在Eclipse中尝试了这段代码,它运行得很好,但在Android中,我正在开发这个应用程序。
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中运行时的输出:"null"并抛出"android.os.NetworkOnMainThreadException"
在Eclipse中运行时的输出:"-97.0" (正确的输出)
发布于 2019-05-04 12:33:06
您需要在另一个线程上运行与网络相关的任务,如下所示:
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Put your code that you want to run in here
} catch (Exception e) {
e.printStackTrace();
}
}现在,如果您不确定导致此问题的原因,您可以检查您的错误日志,它将引导您到导致此问题的行。
您可以做的另一件事是添加带有错误描述的自定义日志/打印,稍后,您可以检查这些日志以查看它们是否被调用(如果是,这意味着您收到了错误)。
发布于 2019-05-04 12:15:04
为了建立网络,您需要使用Asyn Task。下面的链接android中的异步任务给出了一个简单的例子
https://stackoverflow.com/questions/55982375
复制相似问题