0

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!

  • 'Errors like "You can't use Sockets in the main thread'. And indeed you can't. What did you do to resolve this? – greenapps Nov 21 '15 at 18:55
  • Very sloppily asked question. It gives you null if you read past end of stream. It gives you "" if you sent an empty line. If doesn't give you both those things at the same time. It is clear from the answer you've accepted that you're really getting an exception, which has nothing to do with either null or "". *Never* ignore IOExceptions. '"Asynchronous Tasks" or something' is equally sloppy. – user207421 Nov 21 '15 at 22:03
  • I tried to use new Thread().start(); with a Runnable but of course it wasn't working because with the gotten String in the runnable I could not do much. I am sorry, if you think that my question is "sloppy". I try to ask it better the next time. – Luca Vinciguerra Nov 22 '15 at 12:36

1 Answers1

0

Yeah so on Android the threading model means that the "main thread" is what your app is normally running on, as well as executing the code you write, it also executes the code to draw to the screen. Therefore if you did networking on the main thread, your application would become unresponsive, and so the framework puts safeguards in place to catch this early and stop it.

You'll need to do your networking on another thread. I wouldn't normally recommend ASyncTask as a threading solution, but for you as a beginner it is the best thing to get you started.

http://developer.android.com/training/multiple-threads/index.html http://developer.android.com/reference/android/os/AsyncTask.html

ExampleTask task = new ExampleTask();
task.execute();


private class ExampleTask extends AsyncTask<Void, Void, String> {
      @Override
      protected Long doInBackground(Void... notUsed) {
         try {
            client = new Socket(hostname, port);
            BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));
            return is.readLine();

        } catch (Exception e) {
          return "failed " + e.getMessage();
        }

     }

     @Override
     protected void onPostExecute(String result) {
         Vertretungsplan.Cards.add(new VertretungsplanCard("Response:", result));
     }
 }
Blundell
  • 75,855
  • 30
  • 208
  • 233