0

My app is an rss feed and retrieves data when started and when refreshed but when there is no Internet connection the app crashes. How do I check for Internet connection and display a toast if there isn't any

  • Check this link http://www.tutorialspoint.com/android/android_network_connection.htm – Vinothkumar Nataraj Jul 26 '16 at 12:56
  • 3
    refer [How to check internet access on Android? InetAddress never timeouts...](http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts) – Ravi Jul 26 '16 at 12:56
  • lot of examples are their in google http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts – Android Surya Jul 26 '16 at 12:56

3 Answers3

2

You can use this function to check if there is internet

public boolean isConnected() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

You also need to add this to the manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And then just check it

if(isConnected){
    //Connected to the internet
}
else{
    //Handle error and show toast
}

You can find a more detailed answer here How to check internet access on Android? InetAddress never times out

Community
  • 1
  • 1
Isabel Inc
  • 1,871
  • 2
  • 21
  • 28
1

To check is decive connected to network.

private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  return cm.getActiveNetworkInfo() != null;
 }

To check if internet is avalaibe

public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
        }

    }
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
0

Use this function

private boolean isNetworkConnected() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Check Internet connected or not

if(isNetworkConnected){

}

And add below permission in your manifestfile

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Vinothkumar Nataraj
  • 588
  • 2
  • 7
  • 23