java.lang.IndexOutOfBoundsException: Invalid index 4, size is 4

1

I'm not sure what's happening, when I give a long click on an item in the list, sometimes it works normally (opens a screen that shows the user the information registered, allowing it to change it), sometimes the app to and close and sometimes the app stops and opens a registration page by setting the values in the respective fields.

Code that opens the details screen of the registered item:

cDAO.abrirBanco();
contatoArray = cDAO.consultar();

lvContatos.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        Contato c = contatoArray.get(i);

        Intent it = new Intent(MainActivity.this, TelaDetalhe.class);
        it.putExtra("contato", c);
        startActivity(it);

        return true;
    }
});

I get the object sent like this:

final Contato c = (Contato) getIntent().getSerializableExtra("contato");

If I need to put more parts of the code

    
asked by anonymous 03.10.2017 / 16:17

1 answer

6

The error indicates that you are trying to use an index out of range.

In this case you are using index 4 while the array has only 4 items. Remember that index numbering begins with 0 .

The reason for this is that the contatoArray array has fewer items than the array managed by the adapter.

Only with the elements available in the question I can not add anything else.

    
03.10.2017 / 17:18