title: NullPointerException
body: <p>\  Problem is about the NullPointerException that appears in the WifiScanner class while detecting bestsignal. </p>
  
  <pre><code>java.lang.RuntimeException: Unable to start activity
  ComponentInfo{project.e.wifiactivity/project.e.wifiactivity.WifiConnector}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'java.lang.String android.net.wifi.ScanResult.toString()' 
  </code></pre>
  
  <p>\</p>
  
  <pre><code> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
  'java.lang.String android.net.wifi.ScanResult.toString()' on a null object reference
          at
  project.e.wifiactivity.WifiScanner.bestReturn(WifiScanner.java:46)
          at
  project.e.wifiactivity.WifiConnector.onCreate(WifiConnector.java:23)
  </code></pre>
  
  <p>\Logcat</p>
  
  <pre><code>03-30 04:26:07.351  26037-26037/? I/art﹕ Late-enabling -Xcheck:jni  
  03-30 04:26:07.522  26037-26059/project.e.wifiactivity D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true  
  03-30 04:26:07.525  26037-26037/project.e.wifiactivity D/﹕ HostConnection::get() New Host Connection established 0xf3e5c7b0, tid 26037  
  03-30 04:26:07.536  26037-26037/project.e.wifiactivity D/Atlas﹕ Validating map...  
  03-30 04:26:07.573  26037-26059/project.e.wifiactivity D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so  
  03-30 04:26:07.574  26037-26059/project.e.wifiactivity D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so  
  03-30 04:26:07.596  26037-26059/project.e.wifiactivity D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so  
  03-30 04:26:07.607  26037-26059/project.e.wifiactivity D/﹕ HostConnection::get() New Host Connection established 0xeec393f0, tid 26059  
  03-30 04:26:07.628  26037-26059/project.e.wifiactivity I/OpenGLRenderer﹕ Initialized EGL, version 1.4  
  03-30 04:26:07.672  26037-26059/project.e.wifiactivity D/OpenGLRenderer﹕ Enabling debug mode 0  
  03-30 04:26:07.692  26037-26059/project.e.wifiactivity W/EGL_emulation﹕ eglSurfaceAttrib not implemented  
  03-30 04:26:07.692  26037-26059/project.e.wifiactivity W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xeec38740, error=EGL_SUCCESS  
  03-30 04:26:09.662  26037-26059/project.e.wifiactivity W/EGL_emulation﹕ eglSurfaceAttrib not implemented  
  03-30 04:26:09.662  26037-26059/project.e.wifiactivity W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3d0cc60, error=EGL_SUCCESS    
  03-30 04:26:27.858  26037-26037/project.e.wifiactivity D/WifiDemo﹕ onCreate()  
  03-30 04:26:27.936  26037-26059/project.e.wifiactivity W/EGL_emulation﹕ eglSurfaceAttrib not implemented  
  03-30 04:26:27.936  26037-26059/project.e.wifiactivity W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3e840a0, error=EGL_SUCCESS    
  03-30 04:26:28.130  26037-26037/project.e.wifiactivity D/AndroidRuntime﹕ Shutting down VM  
  03-30 04:26:28.130  26037-26037/project.e.wifiactivity E/AndroidRuntime﹕ FATAL EXCEPTION: main  
  Process: project.e.wifiactivity, PID: 26037  
      java.lang.RuntimeException: Unable to start activity ComponentInfo{project.e.wifiactivity/project.e.wifiactivity.WifiConnector}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.wifi.ScanResult.toString()' on a null object reference  
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)  
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  
              at android.app.ActivityThread.access$800(ActivityThread.java:151)  
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  
              at android.os.Handler.dispatchMessage(Handler.java:102)  
              at android.os.Looper.loop(Looper.java:135)  
              at android.app.ActivityThread.main(ActivityThread.java:5254)  
              at java.lang.reflect.Method.invoke(Native Method)  
              at java.lang.reflect.Method.invoke(Method.java:372)  
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  
       **strong text**Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.wifi.ScanResult.toString()' on a null object reference**  
              at project.e.wifiactivity.WifiScanner.bestReturn(WifiScanner.java:46)  
              at project.e.wifiactivity.WifiConnector.onCreate(WifiConnector.java:23)  
              at android.app.Activity.performCreate(Activity.java:5990)  
              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)  
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)  
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  
              at android.app.ActivityThread.access$800(ActivityThread.java:151)  
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  
              at android.os.Handler.dispatchMessage(Handler.java:102)  
              at android.os.Looper.loop(Looper.java:135)  
              at android.app.ActivityThread.main(ActivityThread.java:5254)  
              at java.lang.reflect.Method.invoke(Native Method)  
              at java.lang.reflect.Method.invoke(Method.java:372)  
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
  </code></pre>
  
  <p>\MainActivity class
          /package project.e.wifiactivity;</p>
  
  <pre><code>    import android.content.BroadcastReceiver;
      import android.content.Context;
      import android.content.Intent;
      import android.content.IntentFilter;
      import android.net.wifi.WifiConfiguration;
      import android.net.wifi.WifiInfo;
      import android.net.wifi.WifiManager;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      import android.view.View;
      import android.widget.Button;
      import android.widget.TextView;
      import android.widget.Toast;
  
      import java.util.List;
  
      public class MainActivity extends AppCompatActivity implements View.lickListener {
  
      private static final String TAG="WifiDemo";
      WifiManager wifi;
      BroadcastReceiver receiver;
      public Login login = new Login();
  
  
  
  
      TextView text;
      Button btn;
      Button buttonp;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          text=(TextView)findViewById(R.id.text);
          btn=(Button)findViewById(R.id.btn);
          Button enb = (Button) findViewById(R.id.enb);    v
  
          final  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  
             enb.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if (!wifiManager.isWifiEnabled()) {
                      wifiManager.setWifiEnabled(true);
                      Toast.makeText(MainActivity.this, "Wifi Enabled", Toast.LENGTH_LONG).show();
  
                  }
              }
  
          });
  
          buttonp = (Button) findViewById(R.id.buttonp);
          buttonp.setOnClickListener(this);
          Intent l = new Intent(this, WifiConnector.class);
          startActivity(l);
  
  
  
  
  
  
  
          btn.setOnClickListener(this);
          //get wifi status
          wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
          WifiInfo info=wifi.getConnectionInfo();
          String name = info.getSSID();
          String macid = info.getMacAddress();
          text.append("\n\nWifi Name :"+ name +"\nMac Id :"+ macid);
          //list available network
  
          List&lt;WifiConfiguration&gt; configurations= wifi.getConfiguredNetworks();
          for(WifiConfiguration configuration : configurations){
              text.append("\n\n" +configuration.SSID+"\n"+configuration.BSSID);
          }
  
          //register broadcast receiver
  
          if(receiver==null) {
              receiver = new WifiScanner();
              registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
              Log.d(TAG, "onCreate()");
          }
  
  
  
  
      }
  
  
  
  
  
  
  
  
  
      @Override
      protected void onStop() {
          try {
              this.unregisterReceiver(receiver);
              super.onStop();
          } catch (IllegalArgumentException f) {
              f.printStackTrace();
          }
      }
  
      @Override
      protected void onPause() {
  
  
          try {
              super.onPause();
              unregisterReceiver(receiver);
          } catch (IllegalArgumentException e) {
              e.printStackTrace();
          }
      }
      @Override
      protected void onResume() {
  
  
          super.onResume();
  
          IntentFilter intentFilter = new IntentFilter();
          intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
          registerReceiver(receiver, intentFilter);
  
  
          int f = login.resultp();
  
          if (f == 1) {
              Intent l = new Intent(this, MainActivity.class);
              startActivity(l);
  
          }
      }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
      @Override
      public void onClick(View view) {
      Toast.makeText(getApplicationContext(), "All Network Searched!!", 0).show();
          if (R.id.btn == view.getId()){
               Log.d(TAG, "onCreate() wifi.startScan()");
               wifi.startScan();
  
          }
      }
  }
  </code></pre>
  
  <p>\Wifi Scanner Class</p>
  
  <pre><code>package project.e.wifiactivity;
  
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.net.wifi.ScanResult;
  import android.net.wifi.WifiManager;
  import android.util.Log;
  import android.widget.Toast;
  
  import java.util.List;
  
  
  public class WifiScanner extends BroadcastReceiver {
  
  
  public ScanResult bestsignal ;
  private static final String TAG="WifiScanReceiver";
  MainActivity main;
  
  
  
  
  @Override
  public void onReceive(Context arg0, Intent arg1) {
  
       List&lt;ScanResult&gt; results = main.wifi.getScanResults();
  
  
      for(ScanResult result : results) {
          if(bestsignal == null || WifiManager.compareSignalLevel(bestsignal.level, result.level)&lt;0)
          bestsignal = result;
          bestReturn();
  
  
      }
       String message=String.format("%s networks found.%s is the strongest.", results.size(), bestsignal.SSID);
      Toast.makeText(main, message, 0).show();
      Log.d(TAG, "onReceive() message :"+message);
  
  
  }
  
  public String bestReturn() {
  
      return bestsignal.toString();
  
  }
  </code></pre>
  
  <p>}
  \Wifi Best Signal Connector Class</p>
  
  <pre><code>package project.e.wifiactivity;
  
  
  import android.app.Activity;
  import android.content.Context;
  import android.net.wifi.WifiConfiguration;
  import android.net.wifi.WifiManager;
  import android.os.Bundle;
  
  import java.util.List;
  
  
  
  public class WifiConnector extends Activity {
  
  
  
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          WifiScanner wifiscannner = new WifiScanner();
          String bestnetSSID = wifiscannner.bestReturn();
          String networkPass = "pass";
  
          WifiConfiguration conf = new WifiConfiguration();
          conf.SSID = "\"" + bestnetSSID + "\"";
  
          conf.preSharedKey = "\"" + networkPass + "\"";
  
          WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
          wifiManager.addNetwork(conf);
  
          List&lt;WifiConfiguration&gt; list = wifiManager.getConfiguredNetworks();
          for (WifiConfiguration i : list) {
              if (i.SSID != null &amp;&amp; i.SSID.equals("\"" + bestnetSSID + "\"")) {
                  wifiManager.disconnect();
                  wifiManager.enableNetwork(i.networkId, true);
                  wifiManager.reconnect();
  
                  break;
              }
          }
  
      }
  
  
  }
  </code></pre>
  
  <p>\Manifest</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="project.e.wifiactivity" &gt;
  &lt;uses-feature android:name="android.hardware.wifi" /&gt;
  &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt;
  &lt;uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /&gt;
  &lt;uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" /&gt;
  &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt;
  &lt;uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/&gt;
  
  
  &lt;application
      android:debuggable="true"
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" &gt;
      &lt;activity
          android:name=".Display"
          android:label="@string/app_name" &gt;
          &lt;intent-filter&gt;
              &lt;action android:name="android.intent.action.MAIN" /&gt;
  
              &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
          &lt;/intent-filter&gt;
      &lt;/activity&gt;
      &lt;activity android:name=".Login"&gt;&lt;/activity&gt;
      &lt;activity android:name=".MainActivity"&gt;&lt;/activity&gt;
      &lt;activity android:name=".WifiConnector"&gt;&lt;/activity&gt;
  
  
  &lt;/application&gt;
  
  &lt;/manifest&gt;
  </code></pre>