We can check to see whether a network connection is available using getActiveNetworkInfo() and isConnected() of NetworkInfo class.
This is example is available on Android doc,
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
See here and here for details.
Remember to add permissions in manifest. Follow this step by step tutorial.