Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you catch an UnknownHostException in android?

I'm using HttpClient to post then retrieve something in Android, which works great, but when I dont have a internet connection it forces close, is their a way to catch UnknownHostException when making an HttpPost? I know I could make sure its connected to the internet before making the request, but what about if the phone just doesn't have service?

like image 297
William L. Avatar asked Mar 27 '26 03:03

William L.


2 Answers

UnknownHostException is a Subclass of IOException, so you should be able to catch/manage it simply catching IOException or something more specific (NoRoute, ConnectTimeout, etc.)

Also consider adding connection check before doing network calls with ConnectivityManager

like image 181
Shine Avatar answered Mar 29 '26 18:03

Shine


you can check for your intenet connection with

            ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected() || cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                    //connected
            } else {
                    //not connected
            }

And set the permissions in AndroidManifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
like image 26
Mario Naether Avatar answered Mar 29 '26 17:03

Mario Naether