Search code examples
androidlistviewindexoutofboundsexceptionandroid-wifi

java.lang.IndexOutOfBoundsException: Invalid index 8, size is 0 while scrolling wifi results listview


Hello Guys below is my working wifi connect and results in listview hope they helps who need of that , i am only getting issue on scrolling listview java.lang.IndexOutOfBoundsException: Invalid index 8, size is 0 I tried too much for that set adapter after !=null notify data set changed in different thread and clearing array list before putting into it but none of them works. Please Help!!!!

public class SaveItems extends Activity {
ListView listView;
HashMap arrayList ;
HashMap<String, String> item;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> arraylist2 = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
WifiManager wifi;
Button buttonscan;
ProgressDialog dialog;
private EditText pass;
private String checkPassword = null;
TextView wifiname;
boolean Isnetwork;
boolean wifiEnabled;
Handler handler;
Timer timer;
Timer timer2;
private WifiReceiver wifiReceiver = new WifiReceiver();
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ave_items);

    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    listView = (ListView)findViewById(R.id.lists);


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
             int pos = arg0.getPositionForView(arg1);
                Toast.makeText(getApplicationContext(), "Clicked " + pos, Toast.LENGTH_SHORT).show();

                wifiname.setText(results.get(pos).SSID);
                Log.d("SizeOrig", results.size() + "");
                Log.d("SizepPos", pos + "");

                int hello_size = results.size();
                if (hello_size - 1 == pos) {
                    connectToWifi(hello_size - (pos + 1));
                    Log.d("hello_his","lastitem");
                } else {
                    connectToWifi(hello_size - (pos + 1));
                }

        }

    });




    this.adapter = new SimpleAdapter(SaveItems.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
    if (arrayList!=null){
        if (arrayList.size()!=0) {
            listView.setAdapter(this.adapter);
        }}
    if(listView.getAdapter()==null)
        listView.setAdapter(adapter);
    else{
        adapter.notifyDataSetChanged();
    }
}

public void newWifiResults() {
    dialog.dismiss();
    timer2 = new Timer();
    timer2.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    wifi.startScan();

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

                            arraylist.add(item);

                            size--;
                            adapter.notifyDataSetChanged();
                        }
                    }
                    catch (Exception e)
                    { }

                }
            });
        }
    }, 0, 20000);
}

private void finallyConnect(String checkPassword, int position) {
    String networkSSID = results.get(position).SSID;
    String networkPass = checkPassword;

    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);
}

private void connectToWifi(final int position) {
    Log.d("position",position+"");
    final Dialog dialog = new Dialog(SaveItems.this);
    dialog.setContentView(R.layout.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);
    String inner_pos=results.get(position).SSID;
    Log.d("inner_pos",inner_pos);

    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);
            dialog.dismiss();
        }

    });
    dialog.show();
}

public void onPause() {
    super.onPause();

    if (wifiReceiver!=null) {
        unregisterReceiver(wifiReceiver);
        wifiReceiver=null;
    }
}
public  void onResume(){
    super.onResume();
    try{
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));}
    catch (Exception e){
    }
}
public void onDestroy(){
    super.onDestroy();
    if (wifiReceiver!=null) {
        unregisterReceiver(wifiReceiver);
        wifiReceiver=null;
    }
}
public class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // We are only listening for one type of intent, no verifying necessary
        arraylist.clear();
        results = wifi.getScanResults();
        size = results.size();

        newWifiResults();
    }
}}

Solution

  • if arraylist is your ArrayList which you are passing to the adapter then you have to call adapter.notifyDataSetChanged() after clearing arraylist.clear() in WifiReceiver BroadCastReciever class, because your view is created but after it your ArrayList all objet's has been removed from your arrayList try this:

         public class WifiReceiver extends BroadcastReceiver {
              @Override
              public void onReceive(Context context, Intent intent) {
                // We are only listening for one type of intent, no verifying necessary
                arraylist.clear();
                adapter.notifyDataSetChanged()
                results = wifi.getScanResults();
                size = results.size();
                newWifiResults();
        }
    }
    

    SaveItems:

                        public class SaveItems extends Activity {
                            ListView listView;
                            HashMap arrayList;
                            HashMap<String, String> item;
                            int size = 0;
                            List<ScanResult> results;
                            String ITEM_KEY = "key";
                            ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
                            ArrayList<HashMap<String, String>> arraylist2 = new ArrayList<HashMap<String, String>>();
                            SimpleAdapter adapter;
                            WifiManager wifi;
                            Button buttonscan;
                            ProgressDialog dialog;
                            private EditText pass;
                            private String checkPassword = null;
                            TextView wifiname;
                            boolean Isnetwork;
                            boolean wifiEnabled;
                            Handler handler;
                            Timer timer;
                            Timer timer2;
                            private WifiReceiver wifiReceiver = new WifiReceiver();
                            private int lastViewedPosition = 0;
    
                            @Override
                            protected void onCreate(Bundle savedInstanceState) {
                                super.onCreate(savedInstanceState);
                                setContentView(R.layout.ave_items);
    
                                registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    
                                wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    
                                listView = (ListView) findViewById(R.id.lists);
    
    
                                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
                                    @Override
                                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                                            long arg3) {
                                        int pos = arg0.getPositionForView(arg1);
                                        Toast.makeText(getApplicationContext(), "Clicked " + pos, Toast.LENGTH_SHORT).show();
    
                                        wifiname.setText(results.get(pos).SSID);
                                        Log.d("SizeOrig", results.size() + "");
                                        Log.d("SizepPos", pos + "");
    
                                        int hello_size = results.size();
                                        if (hello_size - 1 == pos) {
                                            connectToWifi(hello_size - (pos + 1));
                                            Log.d("hello_his", "lastitem");
                                        } else {
                                            connectToWifi(hello_size - (pos + 1));
                                        }
    
                                    }
    
                                });
    
    
                                this.adapter = new SimpleAdapter(SaveItems.this, arraylist, R.layout.row, new String[]{ITEM_KEY}, new int[]{R.id.list_value}) {
                                    @Override
                                    public View getView(int position, View convertView, ViewGroup parent) {
                                        lastViewedPosition = position;
                                        return super.getView(position, convertView, parent);
                                    }
                                };
                                if (arrayList != null) {
                                    if (arrayList.size() != 0) {
                                        listView.setAdapter(this.adapter);
                                    }
                                }
                                if (listView.getAdapter() == null)
                                    listView.setAdapter(adapter);
                                else {
                                    adapter.notifyDataSetChanged();
                                }
                            }
    
                            public void newWifiResults() {
                                dialog.dismiss();
                                timer2 = new Timer();
                                timer2.schedule(new TimerTask() {
    
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
    
                                            @Override
                                            public void run() {
    
                                                wifi.startScan();
    
                                                try {
                                                    size = size - 1;
                                                    while (size >= 0) {
                                                        item = new HashMap<String, String>();
                                                        item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities.substring(0, results.get(size).capabilities.indexOf("[")));
    
                                                        arraylist.add(item);
    
                                                        size--;
                                                        adapter.notifyDataSetChanged();
                                                    }
                                                } catch (Exception e) {
                                                }
    
                                            }
                                        });
                                    }
                                }, 0, 20000);
                            }
    
                            private void finallyConnect(String checkPassword, int position) {
                                String networkSSID = results.get(position).SSID;
                                String networkPass = checkPassword;
    
                                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);
                            }
    
                            private void connectToWifi(final int position) {
                                Log.d("position", position + "");
                                final Dialog dialog = new Dialog(SaveItems.this);
                                dialog.setContentView(R.layout.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);
                                String inner_pos = results.get(position).SSID;
                                Log.d("inner_pos", inner_pos);
    
                                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);
                                        dialog.dismiss();
                                    }
    
                                });
                                dialog.show();
                            }
    
                            public void onPause() {
                                super.onPause();
    
                                if (wifiReceiver != null) {
                                    unregisterReceiver(wifiReceiver);
                                    wifiReceiver = null;
                                }
                            }
    
                            public void onResume() {
                                super.onResume();
                                try {
                                    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
                                } catch (Exception e) {
                                }
                            }
    
                            public void onDestroy() {
                                super.onDestroy();
                                if (wifiReceiver != null) {
                                    unregisterReceiver(wifiReceiver);
                                    wifiReceiver = null;
                                }
                            }
    
                            public class WifiReceiver extends BroadcastReceiver {
                                @Override
                                public void onReceive(Context context, Intent intent) {
                                    // We are only listening for one type of intent, no verifying necessary
                                    arraylist.clear();
                                    adapter.notifyDataSetChanged(;
                                    listView.setSelection(lastViewedPosition);
                                    l‌​astViewedPosition = 0
                                    results = wifi.getScanResults();
                                    size = results.size();
                                    newWifiResults();
                                }
                            }
                        }