Search code examples
androidandroid-networking

Check network connection in fragment


I tried to check the network connection in my SherlockFragment but the getSystemService() method is not recognized.

Below is my code (from http://developer.android.com/training/basics/network-ops/connecting.html)

    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        // display error
    }

Thanks in advance


Solution

  • The method getSystemService() is not defined on fragments, so get the activity first using getActivity(), e.g.:

    ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                                 .getSystemService(Context.CONNECTIVITY_SERVICE);
    
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    
    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        // display error
    }
    

    p.s: additianal note: if there is a potential risk that the fragment is running without being attached to any activity, check whether getActivity() returns null first.

    Cheers!