简体   繁体   English

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

[英]“android.os.NetworkOnMainThreadException” even when running in AsyncTask

I'm getting the android.os.NetworkOnMainThreadException error even when I'm running the code inside AsyncTask thread. 即使在AsyncTask线程中运行代码,我也遇到了android.os.NetworkOnMainThreadException错误。 This is basically just a chunk of code that should return me a value from a website. 基本上,这只是一小段代码,应该从网站上为我返回一个值。

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

I'm getting the value with: 我通过以下方式获得价值:

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

The value of "value"- variable is staying the same (presetvalue) and also giving me a android.os.NetworkOnMainThreadException error. “值”-变量的值保持不变(预设值),并且还给了我一个android.os.NetworkOnMainThreadException错误。 I'm really new to any java programming and would appreciate any help. 我真的是任何Java编程的新手,将不胜感激。

You need to execute the AsyncTask, you cannot simply access a static field of it and expect it to give you any result. 您需要执行AsyncTask,您不能简单地访问它的静态字段并期望它会给您任何结果。 You need to do something like that: 您需要执行以下操作:

new BackgroundTask().execute();

Since this is an asynchronous call, it cannot return a result directly (that's what asynchronous means). 由于这是一个异步调用,因此它不能直接返回结果(这就是异步的含义)。 Instead, you get the result in the onPostExecute() method, which is executed in the main thread. 而是在onPostExecute()方法中获得结果,该方法在主线程中执行。

If you are really completely new to Java programming, you should perhaps not start with asynchronous method calls. 如果您真的对Java编程完全陌生,则可能不应该从异步方法调用开始。 That's something, even experienced developers have sometimes problems with. 就是这样,即使是经验丰富的开发人员有时也会遇到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM