I have an AsyncTask which connects to a network resource and tries to read data from the resource. This resource can send data at anytime, so i need the socket to be in the background. When i get a response on the initial connection i receive the message and it is shown on a TextView ont he MainActivity , however when the server sends another message i get error:
06-13 15:46:01.932: I/AsyncTask(1818): doInBackground: Exception Details : Only the original thread that created a view hierarchy can touch its views.
Below is my code:
public class Client extends AsyncTask<Void, byte[], Boolean> {
private String SvrAddr = svradr;
private int Svrport = port;
private InputStream input;
private OutputStream output;
private Socket nSocket;
@Override
protected Boolean doInBackground(Void... params){
boolean rslt = false;
try{
Log.i("AsyncTask", "doInBackground: Creating Socket");
SocketAddress sockad = new InetSocketAddress(SvrAddr,Svrport);
nSocket = new Socket();
nSocket.connect(sockad,5000);
if(nSocket.isConnected()){
input = nSocket.getInputStream();
output = nSocket.getOutputStream();
Log.i("AsyncTask","doInBackground: Socket created.. Streams gotten");
byte[] buffer= new byte[4096];
int read = input.read(buffer,0,4096);
while(read!=-1){
byte[] data = new byte[read];
System.arraycopy(buffer, 0, data,0,read);
Log.i("AsyncTask","doInBackgroiund: got data :" + new String(data,"UTF-8"));
DisplayData(new String(data,"UTF-8"));
read = input.read(buffer,0,4096);
}
}
}catch(IOException ioe){
Log.i("AsyncTask","doInBackground: IO Exception");
rslt=true;
}catch(Exception e){
Log.i("AsyncTask","doInBackground: Exception Details : " + e.getMessage());
rslt = true;
}finally{
try{
input.close();
output.close();
nSocket.close();
}catch(IOException ioe){
}catch(Exception e){
Log.i("AsyncTask","doInBackground: Exception");
rslt = true;
}
Log.i("AsyncTask","doInBackground: Completed");
}
return rslt;
}
private void DisplayData(String msg){
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(msg);
}
}