“NetworkOnMainThreadException”,但在主线程上没有网络调用

时间:2014-01-13 03:35:07

标签: android multithreading

主线程上没有网络调用,但我仍然遇到同样的错误: NetworkOnMainThreadException

MainActivity.class:

public class MainActivity extends Activity
{
    private TextView    tv1,
                        tv2,
                        tv3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        tv3 = (TextView) findViewById(R.id.tv3);

        String xmlUrl = "https://dl.dropboxusercontent.com/s/wbuxa7cutb6/update.xml";

        new DownloadData().execute(xmlUrl);
    }

    public class DownloadData extends AsyncTask<String, Void, InputStream>
    {
        @Override
        protected InputStream doInBackground(String... urls) {
            try {
                URL url = new URL(urls[0]);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(10000);
                connection.setConnectTimeout(15000);
                connection.setRequestMethod("GET");
                connection.setDoInput(true);

                connection.connect();
                int response = connection.getResponseCode();
                Log.d("", "The response is: " + response);

                return connection.getInputStream();
                //return new Scanner(connection.getInputStream(),"UTF-8").useDelimiter("\\A").next();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            return null;    
        }

        @Override
        protected void onPostExecute(InputStream is)
        {
            List<List<String>> lists = new XmlParser().parse(is);

            tv1.setText(lists.get(0).get(0));
            tv2.setText(lists.get(0).get(1));
            tv3.setText(lists.get(0).get(2));
        }
    }
}

您怎么看?互联网的需求仅在 doInBackground()中,但错误仍然存​​在。

日志:

01-13 03:18:37.668: E/AndroidRuntime(5679): FATAL EXCEPTION: main
01-13 03:18:37.668: E/AndroidRuntime(5679): android.os.NetworkOnMainThreadException
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:657)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at libcore.net.http.FixedLengthInputStream.read(FixedLengthInputStream.java:45)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at libcore.io.Streams.readSingleByte(Streams.java:41)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at libcore.net.http.AbstractHttpInputStream.read(AbstractHttpInputStream.java:63)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1623)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:111)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:132)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at neviat.test.downloaddata.XmlParser.parse(XmlParser.java:39)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at neviat.test.downloaddata.MainActivity$DownloadData.onPostExecute(MainActivity.java:70)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at neviat.test.downloaddata.MainActivity$DownloadData.onPostExecute(MainActivity.java:1)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.os.AsyncTask.finish(AsyncTask.java:631)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.os.Looper.loop(Looper.java:137)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at java.lang.reflect.Method.invoke(Method.java:511)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-13 03:18:37.668: E/AndroidRuntime(5679):     at dalvik.system.NativeStart.main(Native Method)

XmlParser的:

public class XmlParser
{
    private DocumentBuilderFactory factory;
    private DocumentBuilder builder;

    private String getNodeValue(NamedNodeMap map, String key) {
        String nodeValue = null;
        Node node = map.getNamedItem(key);
        if (node != null)
            nodeValue = node.getNodeValue();
        return nodeValue;
    }

    public List<List<String>> parse(InputStream inStream)
    {
        List<List<String>> lists = new ArrayList<List<String>>();

        try {
            factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
            builder.isValidating();
            Document doc = builder.parse(inStream, null);

            doc.getDocumentElement().normalize();

            NodeList itemList = doc.getElementsByTagName("item");
            final int length = itemList.getLength();

            for (int i = 0; i < length; i++) {
                final NamedNodeMap attr = itemList.item(i).getAttributes();
                final String dataId         = getNodeValue(attr, "id");
                final String dataName       = getNodeValue(attr, "name");
                final String dataUrl        = getNodeValue(attr, "url");

                List<String> list = new ArrayList<String>();

                list.add(dataId);
                list.add(dataName);
                list.add(dataUrl);

                lists.add(list);
            }
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        return lists;
    }
}

2 个答案:

答案 0 :(得分:2)

引用项目的第一行告诉您错误的位置。

at neviat.test.downloaddata.XmlParser.parse(XmlParser.java:39)

因此,错误实际上位于第39行的XmlParser.java,而不是MainActivity。但是,stacktrace通过查看引用项目的下一行

向我们显示调用它的位置
at neviat.test.downloaddata.MainActivity$DownloadData.onPostExecute(MainActivity.java:70)

所以我们可以看到onPostExecute()中的MainActivity中调用此内容,该UI ThreaddoInBackground()上运行。因此,解决方案是在 List<List<String>> lists = new XmlParser().parse(is); 中运行该行。

lists

但是,根据您使用AsyncTask的其他位置,您需要将其声明为ActivitydoInBackground()的成员变量(无论您需要什么范围)它)。然后,您可以在{{1}}初始化它。

答案 1 :(得分:1)

您正在将InputStream返回到主线程,这意味着您将在onPostExecute方法(在主线程上运行)中执行网络操作。您必须在后台线程中获取所有数据。只有当数据不是来自网络时,您才可以从InputStream解析UI线程上的数据,这不是您的情况。

简而言之,将您的List<List<String>> lists = new XmlParser().parse(is);代码放在doInBackground方法中,然后返回列表。

澄清:您缺少的是Streamings的用途。它们应该被使用,因此您不需要一次加载所有数据(使资源使用,特别是内存消耗,低)。当您将InputStream传递给UI线程时,您不知道已经下载了多少数据(如果有的话)。想象一下,你正在下载一个巨大的XML文件(30MB),你需要解析它。使用InputStream可以避免下载整个内容,将其放入内存(这会使应用程序崩溃),然后解析它。使用Streams,该方法将下载一些数据,解析它并释放已用内存,因此内存消耗总是保持低水平。