Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Array Adapter Selecting the wrong ID

I am building an application that allows the user to connect to their local wifi network without leaving. However, whenever I select an item on the list the wrong network id comes up, and it connects to the wrong network. I've noticed that:

  • If I have three available networks, and I select the top one, the bottom one appears to connect to.
  • The reverse is true as well
  • When I select the middle one it actually works.

Here is my code below:

//from `onCreate` method
Button buttonScan = (Button) findViewById(R.id.buttonScan);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
ListView lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        connectToWifi(arg2);
    }
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        return true;
    }
});

if (!wifi.isWifiEnabled()) {
    Toast.makeText(getApplicationContext(), "Enabling Wifi", Toast.LENGTH_LONG).show();
    wifi.setWifiEnabled(true);
}

SimpleAdapter adapter = 
        new SimpleAdapter(
                NetworkCalibration.this,
                arraylist,
                R.layout.wifi_list_row,
                new String[] { ITEM_KEY },
                new int[] { R.id.listValue });
lv.setAdapter(adapter);

registerReceiver(new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent intent) {
        results = wifi.getScanResults();
        size = results.size();
    }
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

Selecter(hNum, vNum);

buttonScan.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        noob = false;
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("Newbie", noob);
        editor.commit();
        arraylist.clear();
        wifi.startScan();

        Toast.makeText(getApplicationContext(), "Scanning...", Toast.LENGTH_SHORT).show();
        try {
            size = size - 1;
            while (size >= 0) {
                HashMap<String, String> item = new HashMap<String, String>();
                item.put(ITEM_KEY,
                        results.get(size).SSID.toString()
                                + results.get(size).capabilities.toString());

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

public void finallyConnect(String checkPassword, int position) {
    String networkSSID = results.get(position).SSID;
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = "\""+ networkSSID +"\"";
    wifiConfiguration.preSharedKey ="\""+ checkPassword +"\"";
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    int netId = wifiManager.addNetwork(wifiConfiguration);

    if (!wifiManager.isWifiEnabled()) { //---wifi is turned on---
        //---disconnect it first---
        wifiManager.setWifiEnabled(true);
    }
    wifiManager.enableNetwork(netId, true);
    wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, networkSSID);
    wifiManager.reconnect();
    wifiManager.saveConfiguration();

    /* WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", networkSSID);
    wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);

    // remember id
    int netId = wifi.addNetwork(wifiConfig);
    wifi.disconnect();
    wifi.enableNetwork(netId, true);
    wifi.reconnect();

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"\"" + networkSSID + "\"\"";
    conf.preSharedKey = "\"" + networkPass + "\"";
    wifi.addNetwork(conf);*/
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("Connected",isConnected);
    editor.commit();
}

private void connectToWifi(final int position) {
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.wifi_connect);
    dialog.setTitle("Connect to Network");
    TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID1);
    TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID1);
    TextView capabilities = (TextView) dialog.findViewById(R.id.textCapabilities);
    Button dialogButton = (Button) dialog.findViewById(R.id.okButton);
    pass = (EditText) dialog.findViewById(R.id.textPassword);
    pass.requestFocus();
    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.showSoftInput(pass, InputMethodManager.SHOW_IMPLICIT);
    textSSID.setText(results.get(position).SSID);
    textBSSID.setText(results.get(position).BSSID);
    capabilities.setText(results.get(position).capabilities);
    // if button is clicked, connect to the network;
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPassword = pass.getText().toString();
            finallyConnect(checkPassword, position);
            statusText.setText("Connecting...");
            statusText.setTextColor(Color.parseColor("#000000"));
            CheckConnection();
            dialog.dismiss();
        }
    });
    dialog.show();
}

Any idea why this would be happening? Thanks everyone!

like image 862
Ethan Avatar asked Jun 06 '16 00:06

Ethan


2 Answers

I fixed this issue by inverting a few signs in my code and by redefining a few variables. Final working code below:

try {
size = 0;
while (size >= 0) {
HashMap<String, String> item = new HashMap<String, String>();
item.put(
    ITEM_KEY,
    results.get(size).SSID.toString() + results.get(size).capabilities.toString()
);

arraylist.add(item);
size++;
adapter.notifyDataSetChanged();

} catch (Exception e) {
}

And wha'la!

like image 74
Ethan Avatar answered Oct 23 '22 04:10

Ethan


When you add the items to the adapter, you are iterating in an inverse way. That is, your are taking the last item from results and storing it in the first place of arraylist. I suggest you simply inverse the current loop by change this code:

try {
    size = size - 1;
    while (size >= 0) {
    HashMap<String, String> item = new HashMap<String, String>();
    item.put(
        ITEM_KEY,
        results.get(size).SSID.toString() + results.get(size).capabilities.toString()
    );

    arraylist.add(item);
    size--;
    adapter.notifyDataSetChanged();

} catch (Exception e) {
}

for this one:

try {
    for (int i = 0; i < size; i++ ) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put(
            ITEM_KEY,
            results.get(size).SSID.toString() + results.get(size).capabilities.toString()
        );

        arraylist.add(item);
        adapter.notifyDataSetChanged();
    }

} catch (Exception e) {
}
like image 38
josemigallas Avatar answered Oct 23 '22 02:10

josemigallas