title: How to handle with no Internet and lost connection in Android?
body: <p>I have an application that needs to connect to the Internet to perform some actions but when no Internet available it will crash. I read that I need to use try catch bracket in case no Internet. I tried to use it as you can see in AsyncTask but it doesn't work. I don't know why. The app crashes. How to deal with try catch where to put it in my code?</p>
  
  <p>One more thing what about if the app lost Internet connection while process is going on. How supposed I to deal with this thing so my app doesn't crash. Thank you very much.</p>
  
  <pre><code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    lv = (ListView) findViewById(R.id.mybookslistview);
  
    new connectToServer().execute();
  }
  
  
  class connectToServer extends AsyncTask&lt;Void, Void, Void&gt;{
    CustomListViewAdapter adapter;
    HttpResponse response;
    @Override
      protected Void doInBackground(Void... params) {
        ids_list.clear();
        names_list.clear();
        writers_list.clear();
  
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(link);
        ArrayList&lt;NameValuePair&gt; list = new ArrayList&lt;NameValuePair&gt;();
        list.add(new BasicNameValuePair(word, connectionPurpose));
        try {
          post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
          response = client.execute(post);
          BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
          sb = new StringBuffer();
          String tempVar = "";
          while((tempVar = br.readLine()) != null){
            sb.append(tempVar);
          }
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        //Get data from stringbuffer and put it in array list
        if(!sb.toString().trim().contentEquals("null")){
          content_array = sb.toString().split(",");
          for(int s = 0; s &lt; content_array.length; s++){
            if(content_array[s].contains("-")){
              String temp[] = content_array[s].split("-");
              ids_list.add(temp[0].trim());
              names_list.add(temp[1].trim());
              writers_list.add(temp[2].trim());
            }
          }
        }
        return null;
      }
  
    @Override
      protected void onPostExecute(Void result) {
        super.onPostExecute(result);
  
        connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  
        if(!mWifi.isConnected()){
          adb = new AlertDialog.Builder(Home.this);
          adb.setMessage("لا يوجد إنترنت. قم بتفعيل الإنترنت ثم حاول مرة أخرى.");
          adb.setPositiveButton("حاول مجددا", new DialogInterface.OnClickListener() {
  
              @Override
              public void onClick(DialogInterface arg0, int arg1) {
              new connectToServer().execute();
              }
              });
          adb.setNegativeButton("إغلاق التطبيق", new DialogInterface.OnClickListener() {
  
              @Override
              public void onClick(DialogInterface dialog, int which) {
              finish();
              }
              });
          //It shows dialog if no connection
          adb.create().show();
        }else{
          list = new ArrayList&lt;Home.ListViewItem&gt;();
          for(x = 0; x &lt; ids_list.size(); x++){
            list.add(new ListViewItem(){{bookName = names_list.get(x); writerName = writers_list.get(x);}});
          }
          adapter = new CustomListViewAdapter(Home.this, list);
          lv.setAdapter(adapter);
          if(sb.toString().trim().contentEquals("null")){
            Toast.makeText(Home.this, "لا توجد نتائج.", Toast.LENGTH_LONG).show();
          }
        }
  </code></pre>
  
  <p><strong>This is my logcat:</strong>    </p>
  
  <pre><code> java.net.UnknownHostException: Unable to resolve host "globalmall.ca": No address associated with hostname
      at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
      at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
      at java.net.InetAddress.getAllByName(InetAddress.java:214)
      at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
      at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
      at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
      at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
      at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
      at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:1)
      at android.os.AsyncTask$2.call(AsyncTask.java:287)
      at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
      at java.util.concurrent.FutureTask.run(FutureTask.java:137)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
      at java.lang.Thread.run(Thread.java:856)
   Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
      at libcore.io.Posix.getaddrinfo(Native Method)
      at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
      at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
      ... 18 more
   Caused by: libcore.io.ErrnoException: getaddrinfo failed: ENETUNREACH (Network is unreachable)
      ... 21 more
  threadid=13: thread exiting with uncaught exception (group=0x40e582a0)
  </code></pre>