0

I'm trying to make a small Chat app on Android. I'm trying to send some text messages from Android to my server on PC.

I'm using some knowledge that I've found on Android developers and I created a new class for an AsyncTask:

public class ChatTask extends AsyncTask<Void, Void, Void>
{
private BufferedReader in;
private PrintWriter out;


@Override
protected Void doInBackground(Void... voids)
{
    try
    {
        startClient();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}

// Chat start method
private void startClient() throws IOException
{
    Socket socket = new Socket(ipAddress, 9001);

    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);

    writeText("Conectat la serverul: " + ipAddress);

    while (true)
    {
        String line = in.readLine();

        if (line.startsWith("SUBMITNAME"))
        {
            out.println(name);
        }
        else if (line.startsWith("NAMEACCEPTED"))
        {

        }
        else if (line.startsWith("MESSAGE"))
        {
            writeText(line.substring(8) + "\n");
        }
    }
}

// Write to TextView
private void writeText(String text)
{
    ChatActivity.setsTextToSend(text + "\n");
}

// Write to server
public void sendTextToServer(final String text)
{
    Thread thread = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            out.println(text + "\n");;
        }
    });
    thread.start();
}

}

Then I linked the Task with my main Activity. I called the Task.execute() function and it's working well (i think) until the point I write a message and press send. The thing is my message that I write is sent over to the server but the my application crashes and it's giveing me this error:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                  Process: ro.remus.messenger, PID: 3460
                  java.lang.RuntimeException: An error occurred while executing doInBackground()
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at ro.remus.messenger.ChatActivity.writeTo(ChatActivity.java:90)
                      at ro.remus.messenger.ChatActivity.setsTextToSend(ChatActivity.java:26)
                      at ro.remus.messenger.ChatTask.writeText(ChatTask.java:70)
                      at ro.remus.messenger.ChatTask.startClient(ChatTask.java:62)
                      at ro.remus.messenger.ChatTask.doInBackground(ChatTask.java:29)
                      at ro.remus.messenger.ChatTask.doInBackground(ChatTask.java:15)

[ I didn't post the entire error because is not relevant ]

My code in the main activity where the error keeps showing is:

btnSend.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        chatTask.sendTextToServer(getsTextToSend());
                    }
                });

                //textToSend.setText("");
            }
        });

private static void writeTo(String text)
    {
        tvReceivedText.append(text);
    }

I know I'm doing some weird code here but it is doing (somehow) what I want until the point it crashes after I hit 'Send'.

How can I fix this error and stop it from crashing my app ?

Thanks in advance.

Anymore info that is needed I will provide.

R3muSGFX
  • 63
  • 4
  • 12
  • You are getting this error because you are setting the vaule in the background thread which is not permitted in android. To set the value you have to override onPostExecuted and set the value there. @Override protected void onPostExecute(String s) { super.onPostExecute(s); } – AndroidBeginner Jan 29 '17 at 19:58
  • The above link is the first hit I got when searching for "CalledFromWrongThreadException". If it does not answer your question, you should do the same and read the million other hits for the same error. – Code-Apprentice Jan 29 '17 at 20:02
  • @AndroidBeginner thanks for the tip. I will try this to see if it's working. – R3muSGFX Jan 30 '17 at 12:14

1 Answers1

2

As the error say, only the UIThread can make changes to the UI, in this case the TextView. You can use this answer to call sendTextToSend

Community
  • 1
  • 1
X3Btel
  • 1,408
  • 1
  • 13
  • 21