一、問題如下
1、報錯內容:Only the original thread that created a view hierarchy can touch its views.Only the original thread that created a view hierarchy can touch its views.
2、問題分析:在Android中不允許Activity里新啟動的線程訪問該Activity里的UI組件,Android中的UI是線程不安全的, 所有的更新UI操作都必須要在主線程中完成,而不能在新開的子線程中操作。
3、問題背景:
在從Android客戶端向服務器發送數據,並在服務器端處理、返回數據接受之后,要顯示在客戶端的界面上。
由於網絡相關的操作無法在主線程進行,只能通過新線程完成這個操作,而要顯示在客戶端的話,又必須要通過UI線程才能完成,因此就會報出上述錯誤。
這次就是在用Toast顯示服務器端返回的數據時報的這個錯。
二、問題解決
1、若想在異步線程前執行某些UI操作,比如更新progressBar進度條等操作,這種情況適合用runOnUiThread方法。
2、若想在線程中執行UI操作,還是要用Handler:
new Thread(new Runnable() { public void run() { try { URL url = new URL(strUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //設置輸入流采用字節流 urlConnection.setDoInput(true); //設置輸出流采用字節流 urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); //設置緩存 urlConnection.setUseCaches(false); //設置meta參數 urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty("Charset", "utf-8"); //連接往服務器端發送消息 urlConnection.connect(); DataOutputStream dop = new DataOutputStream(urlConnection.getOutputStream()); dop.writeBytes("username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8")); dop.flush(); dop.close(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String result = ""; String readLine = null; while ((readLine = bufferedReader.readLine()) != null) { result += readLine; } bufferedReader.close(); urlConnection.disconnect(); message=URLDecoder.decode(result, "utf-8").toString(); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { Gson gson=new Gson(); Message m=gson.fromJson(message,Message.class); Toast.makeText(LoginActivity.this, m.getMessage(), Toast.LENGTH_LONG).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start();
