Skip to content Skip to sidebar Skip to footer

Alert Dialog Freeze My App

Here there is the code that check the internet connection and then if the isconnected is false show a message in a allert dialog. The problem is that if isconnected is true and (i

Solution 1:

You do not need AsyncTask to check the internet connection, so please keep it simple.

I think that your onClick method should looks like this:

@OverridepublicvoidonClick(View v) {
      if (isConnectionAvailable(context)) {
          // connected
      } else {
          // not connected
      }
};

publicstaticbooleanisConnectionAvailable(Context context) {
    ConnectivityManagermanager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfonetworkInfo= manager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

Do not forget the ACCESS_NETWORK_STATE and INTERNET permissions in your Manifest.

Solution 2:

Try with this...

((Button)findViewById(R.id.listabutton)).setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {

        if(isDeviceOnline(context)){
          //do something.
        }else{
          AlertDialog.Builder dialog= newAlertDialog.Builder(context);
          dialog.setMessage("Not connected");
          dialog.setTitle("Error!");
          dialog.setPositiveButton(.....);
          dialog.create();
          dialog.show();
        } 

    }
}


publicbooleanisDeviceOnline(Context context) {
    ConnectivityManagermanager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfonetworkInfo= manager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

And yes, add ACCESS_NETWORK_STATE and INTERNET permissions in the manifest file

Post a Comment for "Alert Dialog Freeze My App"