2014-11-03 20 views
0

此例程從套接字流(ois)讀取數據。問題是爲什麼它工作正常,顯示通過System.out.println(數據)(用於調試)讀取數據,但它的工作原理錯誤顯示「null」在Android設備的EditText對象時收到數據。Android在EditText中顯示來自套接字連接的變量文本

final EditText input_txt = (EditText) findViewById(R.id.input_txt); 
..... 
thrd = new Thread(new Runnable() { 
    public void run() { 
     while (!Thread.interrupted()) 
     { 
      data = null; 
       try { 
       data = ois.readLine(); 
       } catch (IOException e) {  
        e.printStackTrace(); 
       } 
       if (data != null) 
       { 
        System.out.println(data); 
        runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
        input_txt.setText(data+""); 
        } 
        }); 
       } 
     } 
} 
}); 
thrd.start(); 

-

----- layout xml ------------------------------------- 
.... 
<EditText 
    android:id="@+id/input_txt" 
    android:layout_width="240dp" 
    android:layout_height="match_parent" 
    android:layout_weight="0.25" 
    android:ems="10" 
    android:gravity="top" > 

    <requestFocus /> 
</EditText> 

回答

2

的問題是,你發送一個可運行於UI線程後,您while循環復位數據值(字符串)返回NULL(見註釋代碼)。

//1. Reset data to null, even if 2 is not executed yet. 
data = null; 
    try { 
    data = ois.readLine(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

if (data != null){ 
    Log.d("Test", data); 

    //2. Start this code some where in the future... 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      input_txt.setText(data+""); 
     } 
    }); 
} 

你應該做的是創建一個數據字符串的副本,以便UI線程代碼具有原始數據值。

//1. Reset data to null, even if 2 is not executed yet. 
data = null; 
    try { 
    data = ois.readLine(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

if (data != null){ 
    Log.d("Test", data); 

    //Cache the current value 
    final String dataCopy = data; 
    //2. Start this code some where in the future... 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      input_txt.setText(dataCopy+""); 
     } 
    }); 
} 
+0

你是對的,現在它運行良好。謝謝。 – Alf 2014-11-04 06:59:56