Android JSON解析器错误:http客户端失败
我正在学习JSON解析器。我遵循androidhive教程并复制其代码,但遗憾的是,我不能。它不显示任何内容,并且存在以下类型的错误:Android JSON解析器错误:http客户端失败,android,json,Android,Json,我正在学习JSON解析器。我遵循androidhive教程并复制其代码,但遗憾的是,我不能。它不显示任何内容,并且存在以下类型的错误: 11-22 17:27:12.132: E/AndroidRuntime(1938): Caused by: android.os.NetworkOnMainThreadException 有人能帮我解决这个问题吗?谢谢 杰森帕瑟 import java.io.BufferedReader; import java.io.IOException; impor
11-22 17:27:12.132: E/AndroidRuntime(1938): Caused by: android.os.NetworkOnMainThreadException
有人能帮我解决这个问题吗?谢谢
杰森帕瑟
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
主要活动
import android.view.Menu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity{
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
}
在这段代码中,LogCat捕获我的第二次尝试并打印日志\u connect,http连接中出现错误您有一个NetworkOnMainThreadException错误 这意味着您已经在onCreate方法上直接运行了代码: 但是您不能直接在MainUI线程上更新数据 为此,您必须使用AsyncTask或带处理程序的线程,或使用runOnUiThread()更新您的UI 你可以这样做:
您是否读取了堆栈跟踪 原因:android.os.NetworkOnMainThreadException 如果你在谷歌上搜索“NetworkOnMainThreadException”,你就会得到答案 简而言之,原因是您正在主线程上执行HTTP请求,这实际上是一个糟糕的做法。Android最近变得更加严格,并抛出了一个例外 你需要的是这样的东西:
new AsyncTask<CustomParamClass, Void, String>() {
@Override
protected String doInBackground(final CustomerParamClass... params) {
//use params to get the data and make an HHTP Request.
}
@Override
protected void onPostExecute(final String params) {
// This is invoked on the main thread. Communicate here.
}
}.execute(<pass some params here>);
newasynctask(){
@凌驾
受保护字符串doInBackground(最终CustomerParamClass…参数){
//使用params获取数据并发出HHTP请求。
}
@凌驾
受保护的void onPostExecute(最终字符串参数){
//这是在主线程上调用的。在此处通信。
}
}.execute();
sry我是android的新手,上个月刚开始学习。但是我应该把这个方法放在哪里??main类或JSON解析器类您应该将此方法放在可以执行此类的主类中。为了改进您的问题,最好显示代码。。你是如何得到错误的,你已经尝试了什么,你曾经做过的教程的链接。。很抱歉,我不明白离题的意思。我是新手,在没有适当指导的情况下学习android,我无法定义问题。请原谅我的愚蠢,帮我解决这个问题谢谢
new AsyncTask<CustomParamClass, Void, String>() {
@Override
protected String doInBackground(final CustomerParamClass... params) {
//use params to get the data and make an HHTP Request.
}
@Override
protected void onPostExecute(final String params) {
// This is invoked on the main thread. Communicate here.
}
}.execute(<pass some params here>);