0

I have this code in android and java. I want to show a dialog to the user when his Internet connection has problems or the website is inaccessible. I try to put my code into a try-catch block but yet when the Internet connection has a problem my app is closed. I want to show a message to the user, not to close the app.

 HttpPost ht = new HttpPost("http://yahoo.com");
        HttpClient hc = new DefaultHttpClient();
        HttpResponse hr = null;

        try {
            hr = hc.execute(ht);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        String htmlTemp = "";
        try {

            HttpEntity he = hr.getEntity();

            htmlTemp = new String(EntityUtils.toString(he));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
davide
  • 1,918
  • 2
  • 20
  • 30
  • Do you have a stack trace for the error? Wondering if this a permissions issue? – Droid Chris May 11 '15 at 21:10
  • You could have got an unhandled exception in the first try/catch block, you are catching only ClientProtocolException and IOException. – slanecek May 11 '15 at 21:15
  • You are only catching two very specific types of errors. Start of with a general error handler catch the exception analyse how to handle them and then implement specific error handlers. – Namphibian May 11 '15 at 21:19
  • See [Unfortunately, MyApp has crashed](http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) and [NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception). – nhaarman May 11 '15 at 21:54

2 Answers2

0

you can try to add UnknownHostException to your catch, or you can use this method before calling request :

  public static boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
        Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
      return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
      return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
      return true;
    }

    return false;
  }
Nik Myers
  • 1,843
  • 19
  • 28
0

Did you declare this uses-permission in your manifest file?

<uses-permission android:name="android.permission.INTERNET" />
Jikiwiki
  • 29
  • 2