title: App crashes when there is no internet even though I have added conditions to it
body: <p>Guys my app crashes when there is no internet I have added the following code in MainActivity.java</p>
  <pre><code>import android.Manifest;
  import android.app.AlertDialog;
  import android.app.DownloadManager;
  import android.content.Context;
  import android.content.DialogInterface;
  import android.content.pm.PackageManager;
  import android.net.ConnectivityManager;
  import android.net.NetworkInfo;
  import android.net.Uri;
  import android.os.Build;
  import android.os.Bundle;
  import android.os.Environment;
  import android.util.Log;
  import android.view.View;
  android.webkit.CookieManager;
  import android.webkit.DownloadListener;
  import android.webkit.URLUtil;
  import android.webkit.WebView;
  import android.webkit.WebViewClient;
  import android.widget.LinearLayout;
  import android.widget.Toast;
  
  import androidx.appcompat.app.AppCompatActivity;
  import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
  
  import com.google.android.gms.ads.AdRequest;
  import com.google.android.gms.ads.AdView;
  import com.google.android.gms.ads.interstitial.InterstitialAd;
  import com.google.firebase.messaging.FirebaseMessaging;
  
  public class MainActivity extends AppCompatActivity {
  
  String websiteURL = &quot;https://animenerdyinfo.blogspot.com/&quot;; // sets web url
  private WebView webview;
  SwipeRefreshLayout mySwipeRefreshLayout;
  private LinearLayout noInternetLayout;
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      FirebaseMessaging.getInstance().subscribeToTopic(&quot;notifications&quot;);
  
      AdView adView = (AdView)findViewById(R.id.adView);
      AdRequest adRequest =new AdRequest.Builder().build();
      adView.loadAd(adRequest);
  
      noInternetLayout=findViewById(R.id.noInternetLayout);
  
      checknetwork();
  
      //Swipe to refresh functionality
      mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
  
      mySwipeRefreshLayout.setOnRefreshListener(
              new SwipeRefreshLayout.OnRefreshListener() {
                  @Override
                  public void onRefresh() {
                      webview.reload();
                  }
              }
      );
  
      if(Build.VERSION.SDK_INT&gt;= Build.VERSION_CODES.M){
          if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
  
              Log.d(&quot;permission&quot;,&quot;permission denied to WRITE_EXTERNAL_STORAGE - requesting it&quot;);
              String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
              requestPermissions(permissions,1);
          }
  
  
      }
  
   //handle downloading
  
      webview.setDownloadListener(new DownloadListener() {
          @Override
          public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
  
              DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
              request.setMimeType(mimeType);
              String cookies = CookieManager.getInstance().getCookie(url);
              request.addRequestHeader(&quot;cookie&quot;,cookies);
              request.addRequestHeader(&quot;User-Agent&quot;,userAgent);
              request.setDescription(&quot;Downloading file....&quot;);
              request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
              request.allowScanningByMediaScanner();
              request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
              request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url, contentDisposition, mimeType));
              DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
              dm.enqueue(request);
              Toast.makeText(getApplicationContext(),&quot;Downloading File&quot;, Toast.LENGTH_SHORT).show();
  
  
          }
      });
  
  }
  
  private class WebViewClientDemo extends WebViewClient {
      @Override
      //Keep webview in app when clicking links
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
          view.loadUrl(url);
          return true;
      }
      @Override
      public void onPageFinished(WebView view, String url) {
          super.onPageFinished(view, url);
          mySwipeRefreshLayout.setRefreshing(false);
      }
  }
  
  //set back button functionality
  @Override
  public void onBackPressed() { //if user presses the back button do this
      if (webview.isFocused() &amp;&amp; webview.canGoBack()) { //check if in webview and the user can go back
          webview.goBack(); //go back in webview
      } else { //do this if the webview cannot go back any further
  
          new AlertDialog.Builder(this) //alert the person knowing they are about to close
                  .setTitle(&quot;EXIT&quot;)
                  .setMessage(&quot;Are you sure. You want to close this app?&quot;)
                  .setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                          finish();
                      }
                  })
                  .setNegativeButton(&quot;No&quot;, null)
                  .show();
      }
  }
  
  private void checknetwork(){
      ConnectivityManager connectivityManager= (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      NetworkInfo mobile=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
  
      if (wifi.isConnected()){
          webview.loadUrl(&quot;https://animenerdyinfo.blogspot.com/&quot;);
          webview.setVisibility(View.VISIBLE);
          noInternetLayout.setVisibility(View.INVISIBLE);
      }
      else if (mobile.isConnected()){
          webview.loadUrl(&quot;https://animenerdyinfo.blogspot.com/&quot;);
          webview.setVisibility(View.VISIBLE);
          noInternetLayout.setVisibility(View.INVISIBLE);
      }else{
          webview.setVisibility(View.INVISIBLE);
          noInternetLayout.setVisibility(View.VISIBLE);
      }
  }
  </code></pre>
  <p>}</p>
  <p>And this in my activitymain.xml</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
  xmlns:tools=&quot;http://schemas.android.com/tools&quot;
  android:layout_width=&quot;match_parent&quot;
  android:layout_height=&quot;match_parent&quot;
  tools:context=&quot;.MainActivity&quot;&gt;
  
  &lt;androidx.swiperefreshlayout.widget.SwipeRefreshLayout
      android:id=&quot;@+id/swipeContainer&quot;
      android:layout_width=&quot;match_parent&quot;
      android:layout_height=&quot;match_parent&quot;&gt;
  
      &lt;WebView
          android:layout_width=&quot;fill_parent&quot;
          android:layout_height=&quot;fill_parent&quot;
          android:id=&quot;@+id/webView&quot;
          android:layout_alignParentTop=&quot;true&quot;
          android:layout_alignParentLeft=&quot;true&quot;
          android:layout_alignParentStart=&quot;true&quot;
          android:layout_alignParentBottom=&quot;true&quot;
          android:layout_alignParentRight=&quot;true&quot;
          android:layout_alignParentEnd=&quot;true&quot;
          tools:ignore=&quot;MissingConstraints&quot; /&gt;
  
  &lt;/androidx.swiperefreshlayout.widget.SwipeRefreshLayout&gt;
  
  &lt;LinearLayout
      android:visibility=&quot;invisible&quot;
      android:id=&quot;@+id/noInternetLayout&quot;
      android:layout_width=&quot;match_parent&quot;
      android:layout_height=&quot;match_parent&quot;
      android:background=&quot;#ffff&quot;
      android:orientation=&quot;vertical&quot;
      android:gravity=&quot;center_horizontal&quot;&gt;
  
      &lt;ImageView
          android:layout_width=&quot;250dp&quot;
          android:layout_height=&quot;250dp&quot;
          android:layout_marginTop=&quot;35dp&quot;
          android:src=&quot;@drawable/oops_small&quot;/&gt;
  
      &lt;TextView
          android:layout_width=&quot;wrap_content&quot;
          android:layout_height=&quot;wrap_content&quot;
          android:text=&quot;No Internet&quot;
          android:textSize=&quot;45sp&quot;/&gt;
  
  
  &lt;/LinearLayout&gt;
  
  &lt;com.google.android.gms.ads.AdView
      xmlns:ads=&quot;http://schemas.android.com/apk/res-auto&quot;
      android:id=&quot;@+id/adView&quot;
      android:layout_width=&quot;wrap_content&quot;
      android:layout_height=&quot;wrap_content&quot;
      android:layout_centerHorizontal=&quot;true&quot;
      android:layout_alignParentBottom=&quot;true&quot;
      ads:adSize=&quot;BANNER&quot;
      ads:adUnitId=&quot;ca-app-pub-2422938756578642/8442088186&quot;
      tools:ignore=&quot;MissingConstraints&quot;&gt;
  &lt;/com.google.android.gms.ads.AdView&gt;
  
  &lt;/RelativeLayout&gt;
  </code></pre>
  <p>And this is the error what i get in my logcat</p>
  <pre><code>D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.bestanimewallpapers, PID: 18953
  java.lang.RuntimeException: Unable to start activity 
  ComponentInfo{com.example.bestanimewallpapers/com.example.bestanimewallpapers.MainActivity}: 
  java.lang.NullPointerException: Attempt to invoke virtual method 'void 
  android.webkit.WebView.setVisibility(int)' on a null object reference
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
      at android.app.ActivityThread.-wrap11(Unknown Source:0)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
      at android.os.Handler.dispatchMessage(Handler.java:105)
      at android.os.Looper.loop(Looper.java:164)
      at android.app.ActivityThread.main(ActivityThread.java:6541)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void 
    android.webkit.WebView.setVisibility(int)' on a null object reference
      at com.example.bestanimewallpapers.MainActivity.checknetwork(MainActivity.java:154)
      at com.example.bestanimewallpapers.MainActivity.onCreate(MainActivity.java:53)
      at android.app.Activity.performCreate(Activity.java:6975)
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
      at android.os.Handler.dispatchMessage(Handler.java:105) 
      at android.os.Looper.loop(Looper.java:164) 
      at android.app.ActivityThread.main(ActivityThread.java:6541) 
      at java.lang.reflect.Method.invoke(Native Method) 
      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
      I/zygote: Background concurrent copying GC freed 11556(1403KB) AllocSpace objects, 
      6(116KB) LOS objects, 50% free, 2MB/5MB, paused 3.884ms total 129.262ms
      W/ManagedChannelImpl: [{0}] Failed to resolve name. status={1}
      W/ManagedChannelImpl: [{0}] Failed to resolve name. status={1}
      E/EGL_emulation: tid 19029: swapBuffers(552): error 0x300d (EGL_BAD_SURFACE)
  </code></pre>
  <p>This Code In My AndroidManifest.xml</p>
  <pre><code>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
  &lt;uses-permissionandroid:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;
  &lt;uses-permissionandroid:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;
  /&gt;
  &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot;/&gt;
  </code></pre>
  <p>So guys any one who can tell me where i am wrong and help me with it and i am new to this stuff it would be great if you would tell me in a simple way</p>