Dragg Dragg - 1 month ago 12
Java Question

Connecting to server restarts application

I have setup a Java server on my computer and a client on my Android phone.
However when I launch the app and go to the activity that deals with the client, it restarts the app back to the first activity. This happens when the client method is being executed.

The client code is this

public class ServerInterface extends Activity {

private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String message = "test1";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_interface);

sendCommand("test");




}

public void sendCommand(String command) {
try {


client = new Socket("192.168.100.50", 43596); //Connect to PC server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(command);

printwriter.flush();
printwriter.close();
client.close(); //closing the connection

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


I don't know what's going wrong here.
Thanks.

Answer

You have to run the networking in a async thread. Android does not allow it on the main thread(place inside the class you are to use it in)

private class Connect extends AsyncTask<String, Integer, Boolean> {
     protected Boolean doInBackground(String... urls) {
         try {


        client = new Socket("192.168.100.50", 43596);  //Connect to PC server
        printwriter = new PrintWriter(client.getOutputStream(), true);
        printwriter.write(command);  

        printwriter.flush();
        printwriter.close();
        client.close();   //closing the connection

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
         return false;
     }


 }

Then to do the networking:

new Connect().execute("nullable unless used for dynamic links");