【发布时间】:2014-02-15 19:51:55
【问题描述】:
我尝试从 php 文件中获取 JSON 数据
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
@Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
String punkt = jb.getString("punktezahl");
//String name = jsonarray.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
fuehrender.setText(name);
punkte.setText(punkt);
}
}catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
如果我这样做,我会收到一条消息,即只有创建视图层次结构的原始线程才能接触其视图。
因此,由于此错误消息,我这样尝试:
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
String punkt = jb.getString("punktezahl");
//String name = jsonarray.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
fuehrender.setText(name);
punkte.setText(punkt);
}
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
现在,我收到了NetworkOnMainThread 错误消息。如何突破这个厄运循环?
【问题讨论】:
-
将 try-catch 块放在 AsyncTask 中。
-
简短的回答是:你不能在同一个线程上做网络和 ui。
标签: android json multithreading network-connection