java – 如何在Android中修复NetworkonMainThreadException?
作者:互联网
参见英文答案 > How do I fix android.os.NetworkOnMainThreadException? 53个
我正在创建一个分配项目,我是Android的新手,我想从非常常见的URL http://api.androidhive.info/contacts/访问json,
问题:我正在尝试读取url并获取并解析此url返回的json,
我已经在我的AndroidManifest.xml中添加了以下行
<uses-permission android:name="android.permission.INTERNET"/>
首选项:和我的Android首选项是
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
> Api等级18
> Android 4.3
这就是我试图读取网址的方式
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/
解决方法:
你的异常实际上告诉你你做错了什么.您没有使用其他线程来执行NetworkOperations.相反,您在UI-Thread上执行网络操作,这不能(不)在Android上运行.
连接到url的代码应该在UI-Thread之外的AsyncTasks doInBackground()方法中执行.
看看有关如何使用AsyncTask:How to use AsyncTask的这个问题
标签:android,java,networkonmainthread 来源: https://codeday.me/bug/20191007/1868875.html