0

This routine read the data from a socket stream (ois). The question is why it works fine showing the read data through System.out.println(data) (used to debug) but it works wrong showing "null" in the EditText object of the android device when a data is received.

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>
0

1 Answer 1

2

The problem is that after you send a runnable to the UI thread your while loop resets the data value (String) back to null (See commented code).

//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+"");
        }
    });
}

What you should do is create a copy of the data String so the UI thread code will have the original data value.

//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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.