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

Asked

Viewed 406 times

1

I’m not sure what’s going on, when I long click on a list item, it sometimes works normally (open a screen where it shows the user the registered information, allowing them to change it), sometimes the app stops and closes and sometimes the app stops and opens a registration page 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 pick up the sent object like this:

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

If I need to put more parts of the code

1 answer

7


Error indicates you are trying to use an index outside the range.

In this case you are using index 4 while the array only has 4 items. Note that index numbering starts at 0.

The reason for this to happen is that the array contatoArray has fewer items than the Adapter-managed array.

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

  • what you need most?

  • The part where the Adapter is built. To find out if it is the contactArray that is passed to the Adapter and, if so, if it is "read" ever again after it has been passed.

  • I don’t know if this is what you want to know, but the contactArray contains an arraylist that comes directly from the DAO class search query does not go through the listview Adapter

  • If you do not pass, then you cannot use it to get the "Contact" corresponding to the Listview item clicked. Unless the two are somehow "synchronized".

  • Not what I did but the problem was solved, thanks anyway

Browser other questions tagged

You are not signed in. Login or sign up in order to post.