即使在AsyncTask中运行,也会出现“ android.os.NetworkOnMainThreadException”

时间:2019-05-04 19:23:18

标签: java android

即使我在AsyncTask线程中运行代码,也遇到了android.os.NetworkOnMainThreadException错误。基本上,这只是一小段代码,应该可以从网站上获得我的价值。

package com.jasperhonkasalo.merenpinnankorkeusvsa;

import android.os.AsyncTask;
import android.util.Log;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.util.Iterator;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;




public class NewBackgroundTask {



    public static class BackgroundTask extends AsyncTask<String, Void, String> {

        String value = "presetvalue";

        @Override
        protected String doInBackground(String... urls) {

            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;
                }
            }


            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&";

                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");
                    }
                }
                String xml = sb.toString();

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                Document document = factory.newDocumentBuilder().parse(new InputSource(new StringReader(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) {
                Log.d("EXCEPTIONFAIL", e.toString());
                return "FAIL: " + e.toString();
            }
        }
        @Override
        protected void onPostExecute(String feed) {
            // TODO: do something with the feed
        }
    }
}

我通过以下方式获得价值

static String eeee = new NewBackgroundTask.BackgroundTask().value;

“值”-变量的值保持不变(预设值),并且还给了我一个android.os.NetworkOnMainThreadException错误。我真的是任何Java编程的新手,将不胜感激。

1 个答案:

答案 0 :(得分:2)

您需要执行AsyncTask,您不能简单地访问它的静态字段并期望它会给您任何结果。您需要执行以下操作:

curl -X POST  -H "Authorization: token  mytoken" URL -d '{"key1":"valu1, "key2", "value2"}'

由于这是一个异步调用,因此它不能直接返回结果(这就是异步的含义)。而是在new BackgroundTask().execute(); 方法中获得结果,该方法在主线程中执行。

如果您真的是Java编程的新手,那么也许不应该从异步方法调用开始。就是这样,即使是经验丰富的开发人员有时也会遇到问题。