我正在创建一个分配项目,我是Android新手,我想从非常常见的网址http://api.androidhive.info/contacts/
访问json,
问题:我正在尝试读取网址并获取并解析此网址返回的json,
我已经在我的AndroidManifest.xml中添加了以下行
<uses-permission android:name="android.permission.INTERNET"/>
偏好设置:和我的Android偏好设置
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
这就是我试图阅读网址的方式
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/
答案 0 :(得分:17)
你的Exception
实际上告诉你你做错了什么。您没有使用其他主题来执行 NetworkOperations 。相反,您在UI-Thread上执行网络操作,这不能(不)在Android上运行。
连接到网址的代码应该在 AsyncTasks doInBackground()
方法中执行,关闭UI-Thread。
看看有关如何使用AsyncTask的这个问题: How to use AsyncTask
答案 1 :(得分:12)
在您的活动onCreate
方法
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
答案 2 :(得分:9)
使用以下代码。
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;
}
}
并在您的ManinActivity中使用以下代码。
new UpdateTask().execute();