2

The following gets called with isValid.execute(address), I then call isValid.get() to get the response. However, it hangs and all it's returning is a boolean (true or false),

The bit I use to call the code is:

IsValid isValid = new IsValid();
try {
    isValid.execute(addr);
    success = isValid.get();
}
catch (Exception e) {
    success = false;
}
return success;

IsValid class

public class IsValid extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {
        Boolean success = false;

        try {
            SocketAddress sockaddr = new InetSocketAddress(params[0], 80);

            // Create an unbound socket
            Socket sock = new Socket();

            // This method will block no more than timeoutMs.
            // If the timeout occurs, SocketTimeoutException is thrown.
            int timeoutMs = 2000; // 2 seconds

            Logit(TAG,"" + sockaddr.toString());
            sock.connect(sockaddr, timeoutMs);
            success = true;
        }
        catch (Exception exc) {
            success = false;
        }
        return success;
    }

    @Override
    protected Boolean onPostExceute(Boolean result) {
        Logit(TAG,"IN POST, RESULT IS = "+result);
        return result;
    }
}
HaemEternal
  • 2,229
  • 6
  • 31
  • 50
  • `gets called with isValid.execute(address), I then call isValid.get()`. It is unclear what you precisely do. Please add the calling code to your post. Having said that, you shoulf never call an AsyncTask with .get(). It should be `protected void onPostExceute(Boolean result)` as you cannot return a result. Instead you should handle the result in onPostExecute(). Moreover i think you try to execute an AsyncTask instance twice which is impossable. – greenapps Nov 25 '14 at 12:17
  • So after you posted your calling code we confirm that it is the wrong way. Just use `new IsValid().execute(addr);` and handle result in onPostExecute(). – greenapps Nov 25 '14 at 12:22
  • "onPostExceute" should really be "onPostExecute". – HaemEternal Nov 25 '14 at 13:01

1 Answers1

1

If you read this post: How do I retrieve the data from AsyncTasks doInBackground()?

it looks like you have a similar circumstance. You are starting an asynchronous task, and then waiting for the result, which doesn't make sense.

Instead, you should setup a callback, and use that to get the result

Community
  • 1
  • 1
HaemEternal
  • 2,229
  • 6
  • 31
  • 50