如何在Android中修复NetworkonMainThreadException?
2022-09-02 08:58:03
我正在创建一个用于作业的项目,我是Android的新手,我想从非常常见的url访问json,http://api.androidhive.info/contacts/
问题:我正在尝试读取网址并获取并解析此网址返回的json,
我已经在我的AndroidManifest中添加了以下行.xml
<uses-permission android:name="android.permission.INTERNET"/>
首选项:和我的安卓首选项是
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
- API 级别 18
- 安卓 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/