ur2cdanger
Lurker
I am writing my first android program.Messaging between two emulators.The server side executes fine but I have some problem with the client side.Here is the code :
This is my program for a client emulator.This gives me errors.When I went through the net I found out the error was because the network connection is done is UI thread itself and android>3 does not allow it.Can anybody say how to overcome this?
Code:
package com.app.ServerClient;
import java.io.*;
import java.net.*;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
public class SocketClient extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.0.5";
private static final int REDIRECTED_SERVERPORT = 5000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
tv.setText((CharSequence) serverAddr);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
System.out.println("Here");
} catch (IOException e1) {
e1.printStackTrace();
System.out.println("Here too");
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
This is my program for a client emulator.This gives me errors.When I went through the net I found out the error was because the network connection is done is UI thread itself and android>3 does not allow it.Can anybody say how to overcome this?