The following code crashes when is no interenet connection :
public String gourl(String myurl,String params) {
URL url;
String rasp = "";
try {
url = new URL(myurl + params);
BufferedReader rd = new BufferedReader(new InputStreamReader(
url.openStream()));
String line = "";
while ((line = rd.readLine()) != null) {
rasp=rasp + line;
}
return rasp;
} catch (Exception e) {
Log.w("DHA", "EXCEPTIE URL");
}
return null;
}
How can i prevent this from happening ?
Check connection before execute your method, something like that:
public boolean isNetworkConnected() {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED;
}
Have you checked what the values of myurl and params are in the method?
It may be that url.openStream() is failing and causing a NullPointerException.
It's also helpful to rather do something like:
Log.w("DHA", "EXCEPTIE URL:" + e.toString());
Then you will see what the Exception is rather than having to guess.
Check for all Internet connection
For Wifi
public boolean isWifi(Context context){
try{
WifiManager wifi=(WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
if(wifi.isWifiEnabled()){
return true;
}else{
return false;
}
}
catch(Exception e){
e.getMessage();
return false;
}
}
For Other Network
public boolean isOline(Context context){
try{
ConnectivityManager cm=(ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm==null)
return false;
NetworkInfo info=cm.getActiveNetworkInfo();
if(info==null)
return false;
return info.isConnectedOrConnecting();
}
catch(Exception e){
e.getMessage();
return false;
}
}
If any of them is present then process WS else show alert.And Never forget to mention
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Related
I found a lot of answer about this but unable to implement those also.
I want to implement this code here but not able to do so.
This code I found on google documentation.
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#DetermineConnection
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
}
StringBuilder sb = new StringBuilder();
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
if (is != null) {
is.close();
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
UPDATE:
Update the solution for internet checking. What works for me now is this
fun isNetworkAvailable(context: Context?): Boolean {
if (context == null) return false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
return capabilities != null &&
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
} else {
try {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
} catch (ignored: Exception) {
}
}
return false
}
OLD:
Simple function to check the internet connection
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
}
and in your AndroidManifest.xml you should add the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
protected boolean isNetworkAvilable() {
boolean isNetworkAvilable = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable() && info.isConnected()) {
isNetworkAvilable = true;
}
return isNetworkAvilable;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
return false;
}
like this you can make this method in your common file for your project
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
and use like
if(commonfile.isNetworkAvilable(pass your context here))
{
//call your method
}
and don't forgot to add permission for Internet in your manifeast
what happens if your device connected to internet, but no input data? You also have to check whether you are receiving data or not. Check below code to see you are connected internet and able access data. You just need to ping a site and see if your responce back is 200.
public class internetchek extends AsyncTask<Void,Void,Void> {
public boolean connection;
Context ctx;
public internetchek(Context context){
this.ctx = context;
}
public internetchek(){
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
if(isNetworkAvailable(this.ctx))
{
Log.d("NetworkAvailable","TRUE");
if(connectGoogle())
{
Log.d("GooglePing","TRUE");
connection=true;
}
else
{
Log.d("GooglePing","FALSE");
connection=false;
}
}
else {
connection=false;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.d("GooglePing","IOEXCEPTION");
e.printStackTrace();
return false;
}
}
UPDATE: If you want to use it for other classes you can do this..make sure you put below code in AsyncTask or background running thread.
if(internetchek.isNetworkAvailable(this.ctx)||internetchek.connectGoogle())
{
//Do your stuff here. when you have internet access
}
I am using isConnected() method to test Internet is working or not, However, When Mobile data is on but net is not working (happens when travelling) or Wifi is on but not connected to internet, the method returns true and my app crashes.
I did some finding and found that I need to ping Google also
so I tried using internetConnectionAvailable(1000). Even if Internet is working fine, this method sometimes return false. Can anybody help me with a better solution?
//Check device has Internet connection
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else {
//Custom Toast method
showToast("Unable to connect to Internet !");
return false;
}
}
//ping google and test internet connection
private boolean internetConnectionAvailable(int timeOut) {
InetAddress inetAddress = null;
try {
Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
#Override
public InetAddress call() {
try {
return InetAddress.getByName("www.google.com");
} catch (UnknownHostException e) {
return null;
}
}
});
inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
future.cancel(true);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
Log.e("Google",String.valueOf(inetAddress));
return inetAddress!=null && !inetAddress.equals("");
}
Check whether the internet is connected/not... If yes androidTask() is called.
if (haveNetworkConnection()) {
new androidTask().execute();
} else {
Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
}
Called method of haveNetworkConnection():
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Method contains HTTP request:
class androidTask extends AsyncTask<Void, Void, String> {
String BASE_URL = http://abc.def.com/";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection con = null;
InputStream is = null;
hashMapPost.put("report", "users");
try {
con = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.connect();
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(hashMapPost));
writer.flush();
writer.close();
os.close();
buffer = new StringBuffer();
int responseCode = con.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null)
buffer.append(line).append("\r\n");
is.close();
}
con.disconnect();
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Throwable t) {
}
try {
if (con != null) {
con.disconnect();
}
} catch (Throwable t) {
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
I'm trying to find the way to know when an user has Internet connection, since now I've got this method :
public boolean isNetworkOnline() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(1);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
This method returns true if user is CONNECTED but not if user has INTERNET CONNECTION, so I thought to if this method returns true, call another method to check if the user has connection to internet. For example someone can be connected to a router but without internet connection so I want to know when the user has internet connection or not.
I've read this answer and this other but all of them is returning me false when I've got Internet connection.... I thought that make a method that makes a ping to www.google.com it's a good approach to know if someone has internet connection so I tried to get this way but it didn't work for me...
Any idea or good approach (if it's better than my thoughts is better) to know when the user has internet connection?
The Simple Way To Check Internet Connectivity
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
Process p1 = Runtime.getRuntime().exec(
"ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
if (reachable) {
System.out.println("Internet access");
return reachable;
} else {
return false;
}
} catch (Exception e) {
return false;
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How To Call it
if (isConnectingToInternet()) {
// internet is connected and work properly...
}
else {
// something went wrong internet not working properly...
}
So simply copy and past the above two methods where you want to check the Internet connectivity. After that check the condition if (isConnectingToInternet()) { }
Can you try this method?
public boolean checkInternectConnection() {
try {
InetAddress inAddress= InetAddress.getByName("http://google.com");
if (inAddress.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Please check this answer out and see if its helpful or not
You can try out this code
try {
URL url = new URL("http://"+params[0]);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this is how i fixed this and i use it as a Utility method which can be called from any activity/fragment etc...:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}//check if Wifi or Mobile data is enabled
private static class NetworkAsync extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
return (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0);
} catch (IOException e) {
// Error checking internet connection
}
return false;
}
}//network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException
and now you simply need to call this method from anywhere you want:
public static boolean checkInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
//used execute().get(); so that it gets awaited and returns the result
//after i receive a response
return new NetworkAsync().execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}
My application requires the internet to retrieve data from my database. Also, it uses Google Maps as the main activity. I found that whenever I test it with no internet connection, the screen goes black and then it just crashes. How should I handle this in my code when I have no internet?
try this.......
public boolean isNet()
{
boolean status=false;
String line;
try
{
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(( line = reader.readLine()) != null)
{
}
status=true;
}
catch (IOException ex)
{
System.out.println("ex in isNet : "+ex.toString());
if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
status=false;
}
catch(Exception e)
{
}
return status;
}
if(status==true)
{
//Do your operation
}
else
show("No Internet Connection.");
You can check for internet connection:
public boolean isOnline()
{
//Getting the ConnectivityManager.
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//Getting NetworkInfo from the Connectivity manager.
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//If I received an info and isConnectedOrConnecting return true then there is an Internet connection.
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
and present a message for user if internet connection is not available.
Testing of Network Connection can be done by following method:
public boolean isNetworkAvailable()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
return true;
}
return false;
}
But i don't know how to check the server connection.I had followed this method
public boolean isConnectedToServer(String url, long timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimetout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}
it doesn't works....Any Ideas Guys!!
you can check a server connection is available or not using isReachable():
netAddress address = InetAddress.getByName(HOST_NAME);
boolean reachable = address.isReachable(timeout);
and by using runtime:
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping www.google.com");
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}
and also add intent permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />