Thanks for taking the time to read my question.
I am currently working on one of my first Android App. I am trying to send a String from my Java SocketServer which is running constantly on a VPS to the android app. When I wrote a 10-line client in Eclipse, it worket perfectly. My problem now is how to get the response in Android because I am getting Errors like "You can't use Sockets in the main thread" but the way I wanted to code it is with a method returning the response as a String.
Maybe I should add that my server respsonds with no input/String supplied. I just want to open the connection and read the String from the inputstream.
My Server code where I send:
try {
OutputStream out = socket.getOutputStream();
PrintWriter pw = new PrintWriter(out);
String toSend = "";
//This is just some serialization of own Elements to a string.
boolean first = true;
for (VertretungsPlanElement ele : Main.Elemente) {
if (!first) {
toSend = toSend + "~";
}
first = false;
toSend = toSend + ele.toString();
}
//Serialization ends
pw.println(toSend);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
This method works when I try to get the response from my non-Android client, but it gives me null or "" when I attempt to get it in Android.
My android code:
try {
client = new Socket(hostname, port);
BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));
response = is.readLine();
Vertretungsplan.Cards.add(new VertretungsplanCard("Response:", response));
} catch (Exception e) {}
I did almost a day of research now and I read something about "AsynchronousTasks" or something.
I am sorry if this question has already been asked.
Thanks for your time and your willingness to help!