Android : Android Write in TextView From Thread to UI Thread [duplicate]

on Tuesday, March 24, 2015



I have the following Android code which I am using to receive code from a local server. The Client Server code works as expected. The problem is when trying to get the message from a thread and write it to the TextView. I receive the following error:


03-24 15:08:22.498 22078-22136/com.example.test E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-1029 Process: com.example.test, PID: 22078 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.


My code is here:



public class MainActivity extends Activity {

private ClientComms client;
private PatientData data;
private TextView outputText;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText = (TextView)findViewById(R.id.output);
connectToServer();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onResume()
{
super.onResume();
}


public void connectToServer()
{
Thread t = new Thread(){
public void run() {

try {
outputText.setText("HERE");
client = new ClientComms(**IP Address**, **Port**);


data = new PatientData();
data.setMessage("Test1234");

boolean success = false;
while (success == false) {
success = client.sendToServer(data);
}

if (success) {
outputText.setText("Success");
} else {
outputText.setText("Fail");
}

data = null;

while ((data = client.readSocket()) != null)
{
System.out.println("Read Loop");
outputText.setText(outputText.getText() + " Got data! " + data.getMessage());


data.setMessage("Object Data");

boolean sendData = client.sendToServer(data);

if (sendData) {
System.out.println("Send Successful");
} else {
System.out.println("Send Fail");
}

data = null;


while ((data = client.readSocket()) != null) {
outputText.setText(outputText.getText() + " " + data.getMessage());

data = null;


while ((data = client.readSocket()) != null) {
outputText.setText(outputText.getText() + " " + data.getMessage());
}
}



}
}

0 comments:

Post a Comment