gpt4 book ai didi

java - 如何修复 Android 中的 NetworkonMainThreadException?

转载 作者:太空狗 更新时间:2023-10-29 23:01:03 26 4
gpt4 key购买 nike

<分区>

我正在创建一个作业项目,我是 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" />
  1. API 级别 18
  2. 安卓4.3

这就是我尝试读取 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com