user1732457
user1732457

Reputation: 177

How to know when connection was not established to server?

I am using a server that communicates with my android app, installed in a smartphone. The app is being used in a local environment, and it uses the local ip of the computer to communicate to the apache server over wifi.

The problem is that local ips change from time to time, and when this happens after several time, the app crashes because of some NullPointer exception, because of operation timeout. So i would like to know if there is a way, to know when the connection, to the server, was not successful, and if there is a way to (after acknowledging the operation time out) take some action so that the app does not freeze.

Thnx in advance

I user this code to connect:

HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);


        JSONObject jo = new JSONObject();
        jo.put("tag",tag);




        // Prepare JSON to send by setting the entity
        httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

        // Set up the header types needed to properly transfer JSON
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept-Encoding", "application/json");
        httpPost.setHeader("Accept-Language", "en-US");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();


            is = entity.getContent();

And from this finally a jsonObject is returned, that afterwards i parse to get what i need.

Upvotes: 0

Views: 287

Answers (2)

moh.sukhni
moh.sukhni

Reputation: 2230

you need to use async tasks to do any http calls, otherwise your app will freeze till the operation completed:

start with simple sysnc class to execute your http request. also you need some kind of handlers to get the result back, once the task completed, you can user interfaces or android handler, I like interfaces!

class MyHttpTask extends AsyncTask<View, View, String>
{
    String url = null;
    HttpResultHandler handler = null;
            public final static int ERROR_CONNECTION_TIMEOUT = 1000;
            public final static int ERROR_SOCKET_TIMEOUT     = 2000;
            private int error_code = 0;

    public MyHttpTask(String url, HttpResultHandler handler)
    {
        this.url = url;
        this.handler = handler;
    }

    @Override
    protected String doInBackground(View... arg0)
    {
        try
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            JSONObject jo = new JSONObject();
            jo.put("tag", tag);

            // Prepare JSON to send by setting the entity
            httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

            // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            InputStream is = entity.getContent();

            String result = // read your stream as string or any you might prefer byte[]

            return result;
        }
        catch (UnresolvedAddressException e)
        {
            return null;
        }
        catch (UnknownHostException e)
        {
            return null;
        }
            catch (ConnectTimeoutException e)
             {
                    error_code = ERROR_CONNECTION_TIMEOUT;
                    return null;
             }
           catch(SocketTimeoutException e)
            {
                    error_code = ERROR_SOCKET_TIMEOUT;
                    return null;
            }
        catch (IOException e)
        {
            return null;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (result!=null)
        {
            handler.onSuccess(result);
        }
        else
        {
            handler.OnFailure(errorCode);
        }
    }
}

here is a simple interface that reports success or fail operations:

static interface HttpResultHandler
{
    public void onSuccess(String result);

    public void OnFailure(int errorCode);
}

to test your solution:

private void testHttpTask()
{
     // here you can block the UI using any type of progress bar
    String url = "http://www.something.com";
    new MyHttpTask(url, new HttpResultHandler()
    {

        @Override
        public void onSuccess(String result)
        {
            // TODO Auto-generated method stub
              // here you get success result
             // dismiss any loading progress bars
        }

        @Override
        public void OnFailure(int error_code)
        {
            // TODO Auto-generated method stub
                    // here you get failure
            // dismiss any loading progress bars, and do your recovery stuff

        }
    }).execute();
}

Upvotes: 1

James andresakis
James andresakis

Reputation: 5405

Put up your code where your making your connection. From what you describe it sounds like you need to set your http params so that you have a determined timeout and then catch it some how.

Upvotes: 0

Related Questions