Android在EditText中显示来自套接字连接的变量文本

时间:2014-11-03 23:06:57

标签: java android sockets

此例程从套接字流(ois)读取数据。问题是为什么它通过 System.out.println(data)(用于调试)显示读取数据的工作正常,但它显示错误显示" null"在收到数据时,在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>

1 个答案:

答案 0 :(得分:2)

问题是,在将runnable发送到UI线程之后,while循环会将数据值(String)重置为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+"");
        }
    });
}