0

In my android activity I am using AsyncTask to get data from server using restTemplate and it is working perfectly. I am testing it in my mobile with wifi in my intranet environment as the server is for internal users and I am able to get data from server. But the problem is as sudden I turn Off wifi or change the network, the app crashes (Connection timed out). I know that the URL my app is trying to fetch data is no more accessible from internet but how to prevent app crash or show some notification something like no network. My code is

 private class AsyncTaskRunner extends AsyncTask<String, String, Void> {



        @Override
        protected Void doInBackground(String... params) {


            String username = "user";
            String password = "pass";
            String getAllItems = "http://172.16.243.15:8080/myapp/restGetAllItem";



            HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setAuthorization(authHeader);
            requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            final RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            try{
                ResponseEntity<List> responseEntity=restTemplate.exchange(getAllItems, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), List.class);
                server_response=responseEntity.getBody();
                System.out.println("server response size is"+server_response.size());
            } catch (HttpClientErrorException e){

            }



            return null;
        }

        @Override
        protected void onPostExecute(Void v){


            ProgressBar progressBar=(ProgressBar)getView().findViewById(R.id.progressBar);
            progressBar.setVisibility(getView().GONE);

            RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.card_recycler_view);
            recyclerView.setHasFixedSize(true);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerView.setLayoutManager(layoutManager);
            DataAdapter adapter = new DataAdapter(getContext(), server_response);
            recyclerView.setAdapter(adapter);


        }

    }
ashok
  • 51
  • 2
  • 10
  • share your crash log with question – AskNilesh Oct 27 '17 at 04:40
  • Need to check if a network connection is available first, then make the connection. Still may have an issue if the connection drops out. Need to see crash log as something else might be happening. – Tigger Oct 27 '17 at 04:42
  • share your log cat – A.s.ALI Oct 27 '17 at 05:05
  • You should use a better networking library than AsyncTask if you want HTTP connections to be retried. AsyncTask isn't required to perform HTTP, only to get networking off the main thread. – OneCricketeer Oct 27 '17 at 05:12
  • @Tigger: How to check network connection. I tried ConnectivityManager and NetworkInfo but still app crashing. Reason may be network is connected to the internet but how to check to a specific URL whether reachable or not – ashok Oct 27 '17 at 05:21
  • @cricket_007 actually in my case retried will not help as it would not be able to get connected with internet to my intranet server ever. – ashok Oct 27 '17 at 05:23
  • Well, still. The Volley library exposes a literal `onError` response back on the UI thread. – OneCricketeer Oct 27 '17 at 05:25
  • @ashok : OK, as the server is on a private network you could check the IP of the device, if in a valid range for the private network, connect otherwise alert message. See: [How to get IP address of the device from code?](https://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device-from-code) – Tigger Oct 27 '17 at 05:31
  • @cricket_007 I have not used Volley so far. Can you help me how to make same request and get response from server using Volley. Is it an alternative of restTemplate?. – ashok Oct 27 '17 at 05:56
  • RestTemplate is a spring class. Unless you are using Spring-Android / Spring Boot, then I would avoid compile anything Spring related to reduce app size. The documentation is fine https://developer.android.com/training/volley/index.html – OneCricketeer Oct 27 '17 at 06:10

2 Answers2

0

You also need to handle multiple exceptions such as this for different reasons, You only catched the CLienErrorException

also add something like this to handle exception

try{
//Your Connection Code

} catch (HttpClientErrorException e){
  Log.e(LOG_TAG, "Client Error", e);
  // Do something else, if wanted.

}
catch (InterruptedIOException iioe)
{
   // Exception thrown when network timeout occurs
   System.err.println ("Remote host timed out during read operation");
}
catch (IOException e)
{
  Log.e(LOG_TAG, "Connection Error", e);
  // Do something else, if wanted.
}
catch(Exception e)
{
  //Do Something
}
finally
{
  //Do Something
}
Niraj Sanghani
  • 1,493
  • 15
  • 23
0

When an exception occurs due to network error, the value of server_response will not be set resulting it to be null.

You may use <String, String, Boolean> as type of your AsyncTask and return false inside the catch block so that inside the onPostExecute method you can check the boolean result whether the result was obtained or not. If the result is false, you can show an error toast and return.

Alternatively, you can also check for null condition for the value server_response before using it inside the onPostExecute method.

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59