Search code examples
androidadapterandroid-adapterandroid-wifiwifimanager

Android: trouble in understanding wifi receiver and adapter concepts used to scan WiFi APs and list them in listview


public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener{

// Declare View variables
private Button mRefreshButton;
private Switch mWifiSwitch;
private ListView mAPListView;
private List<ScanResult> mWifiList;
private List<String> mListOfProviders;
private ListAdapter mAdapter;
private WifiManager mWifiManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mListOfProviders = new ArrayList<String>();
    mAPListView = (ListView) findViewById(R.id.APListView);
    mRefreshButton = (Button) findViewById(R.id.refreshButton);
    mWifiSwitch = (Switch) findViewById(R.id.WiFiSwitch);
    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    boolean wasEnabled = mWifiManager.isWifiEnabled();
    if (wasEnabled){
        mWifiSwitch.setChecked(true);
    }
    mWifiSwitch.setOnCheckedChangeListener(this);

    //wifiReciever = new WifiScanReceiver();
    mWifiManager.startScan();
    mWifiList = mWifiManager.getScanResults();

}


@Override
public void onClick(View view)
{

}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked){
        mWifiManager.setWifiEnabled(true);
    }
    else {
        mWifiManager.setWifiEnabled(false);
    }
}

}

I am extremely new to Android development and simply building an android app to scan available APs and list them.

However, I am having a trouble in understanding concepts and usages of adapter and wifi receiver which are used most for building those functionalities.

Would you help me out what I should do to actually store and display the AP info after starting scanning?

Thank you.


Solution

  • You have already created the ListView and generated the List of available connections, so most of your work is done. What is left to do is to fill the ListView with the objects in the list, to do that you need to use an Adapter.

    But first you should add the names of the connections to the List<String> that you have created:

    for ( ScanResult result :  mWifiList ) { 
     mListOfProviders.add( result.SSID); //This will add the SSID of the connection
    }
    

    And then you will pass this list to the ArrayAdapter

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, mListOfProviders);
    mAPListView.setAdapter(adapter);
    

    Good Luck :)