Functioning Socket read no longer works when called in AsyncTask
- by bibismcbryde
I'm making an app that sends a string to a server over a socket and then reads the output after the server has processed that data. It worked perfectly when it was my foreground task, but I have since used AsyncTask to show a process dialog while the socket communication runs in the background, and things start breaking after I read the output from the server and then try to close the socket.
private class Progressor extends AsyncTask<String, Void, Void> {
        ProgressDialog dialog;
        protected void onPreExecute() {
            dialog = ProgressDialog.show(ClearTalkInputActivity.this, "Loading..", "Analyzing Text", true, false);
        }
        protected Void doInBackground(String... strings) {
            String language = strings[0].toLowerCase();
            String the_text = strings[1];
            Socket socket = null; 
            DataOutputStream dos = null;
            DataInputStream dis = null;
            try {
                socket = new Socket(my_ip, port);
                dos = new DataOutputStream(socket.getOutputStream());
                dis = new DataInputStream(socket.getInputStream());
                dos.writeUTF(language+"****"+the_text);
                String in = "";
                while (in.indexOf("</content>") < 0) {
                    in += dis.readUTF();    
                }
                socket.close();
                save_str(OUTPUT_KEY, in);   
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
            } 
            finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } 
            return null;
        }
    protected void onPostExecute() {
        if (dialog.isShowing())
            dialog.dismiss();
        startActivity(new Intent (output_intent));
    }
}