Skip to content Skip to sidebar Skip to footer

Data From Android Mobile To Java Application Through Socket

I want to transfer data from Android device to the java desktop server. I have a text and button. As I press the button on the device, the text should be displayed on the java desk

Solution 1:

Your code seems very confusing. The client seems to have code for doing the network connection and I/O both on the main thread (in the OnClickListener attached to button) and in the AsyncTask (which is never created). Try this for an OnClickListener:

button.setOnClickListener(newView.OnClickListener() {

    publicvoidonClick(View v) {
        message = textField.getText().toString(); //get the text message on the text field
        textField.setText("");      //Reset the text field to blanknewAsynctask().execute(message);
    }
});

But you have another problem: while your AsyncTask is (correctly) making the socket connection in doInBackground, it is incorrectly doing the network I/O in onPostExecute. The network I/O also needs to be done in the background. Try this for an AsyncTask:

publicclassAsynctaskextendsAsyncTask<String, Void, Void> {
    privatestaticfinalString IP_ADDRESS = "134.190.162.165";  // Toshiba laptop//  private static final String IP_ADDRESS = "10.0.0.2";  // Toshiba laptopprivatestaticfinalint DEST_PORT = 4444;

    private EditText mTextField;

    /**
     * Store provided views (used later in onPostExecute(...)).
     * 
     * Create socket to communicate with server (blocking call).
     */protectedVoid doInBackground(String... messages) {
        if (messages.length != 1) { returnnull; }
        String message = messages[0];

        // Create socket.
        Socket client = null;

        try {
            client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Write to server.try {
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage); // write the message to output stream

            printwriter.flush();
            printwriter.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The above is entirely untested, so it may not be exactly right. I also didn't look at your server code; this answer just addresses the NetworkOnMainThreadException problem.

Post a Comment for "Data From Android Mobile To Java Application Through Socket"