在BroadcastReciever

时间:2015-04-30 12:37:58

标签: android listview arraylist broadcastreceiver wifi

我正在开发应用程序,在那里我获得可用的wifi连接并在listview中显示它。但是,当我想将连接名称字符串值添加到Arraylist时,它会给我一个错误。帮我解决这个问题。 这是我的代码

public class HackActivity extends Activity {
    TextView mainText;
    WifiManager wifi;
    WifiReceiver receiver;
    List<ScanResult> scanList;
    ArrayList<String> wifiList;
    ListView list;
    ArrayAdapter<String> adapter;
    StringBuilder sb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hack);
        mainText = (TextView) findViewById(R.id.txtMain);
        list=(ListView) findViewById(R.id.list_wifi);
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false) {
            wifi.setWifiEnabled(true);
            Toast.makeText(getApplicationContext(), "Enabled",
                    Toast.LENGTH_LONG).show();
        }

        receiver = new WifiReceiver();
        registerReceiver(receiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        wifi.startScan();
        mainText.setText("Scaning connections...");
    }

    public class WifiReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context ctx, Intent intent) {
            sb = new StringBuilder();
            scanList = wifi.getScanResults();
            sb.append("\n        Number Of Wifi connections :"
                    + scanList.size() + "\n\n");
            for (int i = 0; i < scanList.size(); i++) {
                //sb.append((scanList.get(i)).SSID);
                 wifiList.add((scanList.get(i)).SSID);
            }
             adapter=new
             ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifiList);
             list.setAdapter(adapter);
            mainText.setText(sb);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "Refresh");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        wifi.startScan();
        mainText.setText("Starting Scan");
        return super.onMenuItemSelected(featureId, item);
    }

    protected void onPause() {
        unregisterReceiver(receiver);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(receiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

}

1 个答案:

答案 0 :(得分:0)

你还没有初始化wifiList:

    ArrayList<String> wifiList;

必须在onCreate:

    wifiList = new ArrayList<String>();