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.