Java 如何修复 Android 中的 NetworkonMainThreadException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19740604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix NetworkonMainThreadException in Android?
提问by zzlalani
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/
,
我正在创建一个分配项目,我是 Android 新手,我想从非常常见的 url 访问 json http://api.androidhive.info/contacts/
,
Problem:I'm trying to read the url and fetch and parse the json returned by this url,
问题:我正在尝试读取 url 并获取并解析此 url 返回的 json,
I've already added following line into my AndroidManifest.xml
我已经将以下行添加到我的 AndroidManifest.xml 中
<uses-permission android:name="android.permission.INTERNET"/>
Preferences:and my android preferences are
首选项:我的 android 首选项是
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
- Api level 18
- Android 4.3
- API 级别 18
- 安卓 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();
The Error Message
错误信息
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.access0(ActivityThread.java:141)
11-02 05:23:47.843: E/AndroidRuntime(2207): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
Also I'm following this tutorial for ListView Example http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
此外,我正在关注本教程的 ListView 示例 http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
采纳答案by Philipp Jahoda
Your Exception
actually tells you exactly what you are doing wrong. You are not using another threadto perform NetworkOperations. Instead, you perform the network operation on your UI-Thread, which cannot (does not) work on Android.
你Exception
实际上告诉你你做错了什么。您没有使用另一个线程来执行NetworkOperations。相反,你在你的 UI-Thread 上执行网络操作,这不能(不)在 Android 上工作。
Your code that connects to the url should be executed for example inside an AsyncTasksdoInBackground()
method, off the UI-Thread.
连接到 url 的代码应该在AsyncTasksdoInBackground()
方法中执行,例如在UI 线程之外。
Take a look at this question on how to use the AsyncTask: How to use AsyncTask
看看这个关于如何使用 AsyncTask 的问题:How to use AsyncTask
回答by Jitesh Dalsaniya
Use following code.
使用以下代码。
private class UpdateTask extends AsyncTask<String, String,String> {
protected String doInBackground(String... urls) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
return null;
}
}
and in your ManinActivity Use following code.
并在您的 ManinActivity 中使用以下代码。
new UpdateTask().execute();
回答by Giru Bhai
Updated Answer:
更新答案:
Potentially long running operations such as networkoperations should be done in a worker thread.
可能长时间运行的操作(例如网络操作)应该在工作线程中完成。
The most effective way to create a worker thread for longer operations is with the AsyncTaskclass. Simply extend AsyncTaskand implement the doInBackground()method to perform the work.
为更长的操作创建工作线程的最有效方法是使用AsyncTask类。只需扩展AsyncTask并实现doInBackground()方法来执行工作。
Many libraries are available to do network operations such as Volley, retrofitetc.
Old Answer:
旧答案:
Add following lines in your activity onCreate
method
在您的活动onCreate
方法中添加以下几行
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);