如何在Android中修复NetworkonMainThreadException? [英] How to fix NetworkonMainThreadException in Android?

查看:92
本文介绍了如何在Android中修复NetworkonMainThreadException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个要分配的项目,我是Android的新手,我想从非常常见的URL http://api.androidhive.info/contacts/中访问json,

I'm creating an project for assignment, I'm new to Android, and I wanted to access json from very common url http://api.androidhive.info/contacts/,

问题::我正在尝试读取网址,并获取并解析此网址返回的json,

Problem: I'm trying to read the url and fetch and parse the json returned by this url,

我已经将以下行添加到我的AndroidManifest.xml

I've already added following line into my AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

首选项:我的android首选项是

Preferences: and my android preferences are

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

  1. Api 18级
  2. Android 4.3

这就是我试图读取网址的方式

and this is how I'm trying to read the url

static InputStream is = null;

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

错误消息

11-02 05:23:47.843: E/AndroidRuntime(2207): FATAL EXCEPTION: main
11-02 05:23:47.843: E/AndroidRuntime(2207): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.countrypedia/com.me.countrypedia.MainActivity}: android.os.NetworkOnMainThreadException
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

我也在关注本教程的ListView示例 http://www.androidhive.info/2011/11/android- xml-parsing-tutorial/

Also I'm following this tutorial for ListView Example http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

推荐答案

您的Exception实际上告诉您您做错了什么.您没有使用其他线程来执行 NetworkOperations .而是在UI-Thread上执行网络操作,而该操作在Android上不能(不起作用).

Your Exception actually tells you exactly what you are doing wrong. You are not using another thread to perform NetworkOperations. Instead, you perform the network operation on your UI-Thread, which cannot (does not) work on Android.

例如,应该在 AsyncTasks doInBackground()方法内,关闭UI线程内执行连接到url的代码.

Your code that connects to the url should be executed for example inside an AsyncTasks doInBackground() method, off the UI-Thread.

看看有关如何使用AsyncTask的问题: 如何使用AsyncTask

Take a look at this question on how to use the AsyncTask: How to use AsyncTask

这篇关于如何在Android中修复NetworkonMainThreadException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆