-2

For short, I have been making a PC <---> Android chat using simple sockets and print writers. I have the PC client and server working, all I cannot get to work is android because I am really new to it. Could anyone help me out whey I am getting this error when I try to connect?

FYI: I did look up on google and the rest of stackoverflow on asynctask, but nothing is clear. I am trying to understand how it works but no example is coming close. I changed the code so my connectButton onClickListener starts a new ServerTask (this is the AsyncTask) and I put it in the code that I used to use on the onClickListener. I had to comment out the exception because it was writing to the UI in doInBackground which apparently is not possible. I just don't understand why I cannot connect if I started the new AsyncTask

    package com.example.JurkoAndroidChat;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;

import java.net.*;
import java.io.*;
import java.util.*;



public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    // Right here, we connecting the components of the main.xml form to code
    Button connectButton, disconnectButton, sendButton;
    TextView chatArea, clientArea;
    EditText messageField, usernameField, ipField;

    //Extra variables and sockets
    String username, serverIP;
    int Port = 5000;
    Socket sock;
    PrintWriter out;
    BufferedReader in;
    ArrayList<String> userList;
    Boolean isConnected = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        System.out.println("Working?");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        userList = new ArrayList();
        connectButton = (Button)findViewById(R.id.button);
        sendButton = (Button)findViewById(R.id.button1);
        disconnectButton = (Button)findViewById(R.id.button2);

        chatArea = (TextView)findViewById(R.id.textView2);
        clientArea = (TextView)findViewById(R.id.textView3);

        messageField = (EditText)findViewById(R.id.editText2);
        usernameField = (EditText)findViewById(R.id.editText);
        ipField = (EditText)findViewById(R.id.editText1);

        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //To change body of implemented methods use File | Settings | File Templates.
                if (isConnected == false) {
                    username = usernameField.getText().toString();
                    usernameField.setFocusable(false);
                    usernameField.setClickable(false);
                    serverIP = ipField.getText().toString();
                    ipField.setFocusable(false);
                    ipField.setClickable(false);
                    executeTask();

                } else if (isConnected == true) {
                    chatArea.append("You are already connected to the server.\n");
                }
            }
        });

        disconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //To change body of implemented methods use File | Settings | File Templates.
                String bye = (username + ": :Disconnect");
                try {
                    out.print(bye);
                    out.flush();
                    chatArea.append("Disconnected.\n");
                    sock.close();

                } catch (Exception e) {e.printStackTrace();}
                isConnected = false;
                usernameField.setFocusable(true);
                usernameField.setClickable(true);
                ipField.setFocusable(true);
                ipField.setClickable(true);
                clientArea.setText("");
            }
        });

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //To change body of implemented methods use File | Settings | File Templates.
                String nothing = "";
                if ((messageField.getText().toString().equals(nothing))) {
                    messageField.setText("");
                    messageField.requestFocus();
                } else {
                    try {
                        out.println(username + ":" + messageField.getText().toString() + ":" + "Chat");
                        out.flush();
                    } catch (Exception e) {
                        chatArea.append("Message was not sent.\n");
                    }
                    messageField.setText("");
                    messageField.requestFocus();
                }
            }
        });


    }

    public class ServerTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Log.i("Asynctask", "doInBackground");
                sock = new Socket(serverIP, Port);
                out = new PrintWriter(sock.getOutputStream());
                in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                out.println(username + ":" + "has connected." + ":" + "Connect");
                out.flush();
                isConnected = true;

            } catch (Exception ex) {
//                    chatArea.append("Unable to connect to " + serverIP + " at port " + Port + "." + ex);
//                    ex.printStackTrace();
//                    usernameField.setFocusable(true);
//                    usernameField.setClickable(true);
//                    ipField.setFocusable(true);
//                    ipField.setClickable(true);

            }


                ListenThread();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
           //To change body of overridden methods use File | Settings | File Templates.
        }

    }

    public void executeTask() {
        new ServerTask().execute();
    }

    public class IncomingReader implements Runnable {
        @Override
        public void run() {
            //To change body of implemented methods use File | Settings | File Templates.
            String[] data;
            String stream, done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat";

            try {
                while ((stream = in.readLine()) != null) {
                    data = stream.split(":");

                    if (data[2].equals(chat)) {
                        chatArea.append(data[0] + ": " + data[1] + '\n');
                    } else if (data[2].equals(connect)) {
                        chatArea.setText("");
                        userAdd(data[0]);
                    } else if (data[2].equals(disconnect)) {
                        userRemove(data[0]);
                    } else if (data[2].equals(done)) {
                        clientArea.setText("");
                        writeUsers();
                        userList.clear();
                    }


                }
            }  catch (Exception e) {e.printStackTrace();}
        }
    }

    public void ListenThread() {
        Thread IncomingReader = new Thread(new IncomingReader());
        IncomingReader.start();
    }



    public void userAdd(String data) {
        userList.add(data);
    }

    public void userRemove(String data) {
        chatArea.append(data + " has disconnected from the server.\n");
        for (String token:userList)
            if (token.equals(data))
                userList.remove(token);
    }

    public void writeUsers() {
        String[] tempList = new String[(userList.size())];
        userList.toArray(tempList);
        for (String token:tempList) {
            clientArea.append(token + '\n');
        }
    }








}
Jurko Guba
  • 630
  • 7
  • 17
  • 4
    That's a duplicate of... a thousand other questions. Just google for `NetworkOnMainThreadException`. – Ahmad Oct 08 '13 at 23:47
  • Although you should hardly need to. The exception *name* is self-explanatory, and if that doesn't help you, read its Javadoc. – user207421 Oct 09 '13 at 00:29

1 Answers1

0

You cannot do networking on the main thread, you have to create a new one or an AsyncTask in order to do any Networking operation.

http://developer.android.com/reference/android/os/AsyncTask.html

HappyDump
  • 443
  • 9
  • 18
  • Are you saying you can't do networking in `AsyncTask`? – codeMagic Oct 09 '13 at 00:02
  • 1
    Thank you I didn't see I typed too fast. it is edited! – HappyDump Oct 09 '13 at 00:06
  • Edited to use with AsyncTask. I understand how it works but I am still really puzzled why I can't connect / how this affects me sending messages. Here is what I understand. Click connect: Starts a new AsyncTask which is like a different thread so it should solve the NetworkOnMainThread problem: Then ListenThread() executes another thread to parse the message. This should all still be running yes or does garbage collection somehow pick it up?? Thank you very much. – Jurko Guba Oct 09 '13 at 03:40