In AsynsTask I send a get request

try { URL url = new URL(params[0]); urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); } catch (Exception e) { httpClient.onError(e.getMessage()); return null; } 

When there is an Internet connection, everything is fine, but when there is no application terminates with an error. Question. How to solve this problem?

1 answer 1

You can check the presence of the connection before sending the request, and if it is, send the request, otherwise give a message about the absence of the connection. looks like this:

  if (!isOnline()) { connectDialog(); }else{ // do need work} 

connection check:

  protected boolean isOnline() { String cs = Context.CONNECTIVITY_SERVICE; ConnectivityManager cm = (ConnectivityManager) getSystemService(cs); return cm.getActiveNetworkInfo() != null; } 

no connection message:

  public void connectDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Нет доступа к интернету"); builder.setMessage("Для работы с приложением требуется соединение с интернетом.\n" + "Включите доступ к интернету!"); builder.setCancelable(false); builder.setPositiveButton("Ок", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); } 
  • This is an option, but, as far as I know, the proposed code checks only the presence of a connection to the -l network, but not the presence of the Internet in it. In addition, the Internet may disappear after the start of the request. - Yuriy SPb
  • @Yuriy SPb yes you are right, can I find out your version? - Sergey
  • @YuriySPb what do you think is better to catch the error about the absence of the Internet and process it or constantly check its availability? I want to know your expert opinion - Sergey
  • IMHO, it is better to catch a connection error than to check the availability of the Internet, because it can appear / disappear at any time and any info about its availability will be relevant only at the time of the check) - Juriy Spb