Search code examples
javaandroidclassandroid-wifi

Wifi scanner with 20 scanning purpose


I was trying to built an array of class and was putting some values to the objects but still it is showing null pointer exception.

my code is :

class WifiScanReceiver extends BroadcastReceiver {
          @SuppressLint("UseValueOf")
          public void onReceive(Context c, Intent intent) {

              List<ScanResult> wifilist = wifi.getScanResults();
                 info = wifi.getConnectionInfo();
                int k = wifilist.size(); 


                scan_data[] data = new scan_data[k];

             for (int i=0;i<20;i++){
                wifi.startScan();
                List<ScanResult> wifilist1 = wifi.getScanResults();

                int l = wifilist1.size();

                if (i==0){
                for (int j=0;j<l;j++){
                    data[j].ssid = wifilist1.get(j).SSID.toString();
                    data[j].bssid = wifilist1.get(j).BSSID.toString();
                    data[j].lvl = wifilist1.get(j).level;
                    data[j].count++;
                }

If you could tell me why its is showing null pointer exception at

data[j].ssid = wifilist1.get(j).SSID.toString();

Solution

  • Problem is your scan_Data array is not initialized with objects.

    scan_data[] data = new scan_data[k];
    

    this is just initializing the array not putting objects in it. you have to do it explicitly So in your for loop. Create scan_data object and put all the values in it and then put that on data[j].

             for (int j=0;j<l;j++){
                    scan_data sData = new scan_data();
      //            set all desired values in sData from ScanData
                    data[j] = sData;
                }
    

    Hope this helps.