我試着從一個php文件如何解決問題與mainthread
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();
}
得到JSON數據如果我做這樣我得到的消息只有創建一個視圖層次可以觸摸其觀點原來的線程。
是因爲此錯誤消息我試着像這樣的:
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
錯誤信息。如何通過這個厄運循環打破?
發生的AsyncTask您try-catch塊的。 –
簡短的回答是:你不能在同一個線程上聯網**和** ui。 – njzk2