Error with array (java.lang.ArrayIndexOutOfBoundsException: length = 5; index = 5)

1

I have an array that has several elements, all this contained in a database, but when I want to delete it with a method (with split) it does not leave me and it throws me the error of the title, how do I solve it ?, and all this , how can I see how the array is changing as the application works ?, attached code

View events:

public class ViewEventsActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener {
//al mantener la wea apretada
private SQLiteDatabase db;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_events);

    listView=(ListView) findViewById(R.id.ltvListaEventos);
    listView.setOnItemLongClickListener(this);

    Bundle bundle= getIntent().getExtras();
    int dia,mes,anio;
    dia=mes=anio=0;

    dia=bundle.getInt("dia");
    mes=bundle.getInt("mes");
    anio=bundle.getInt("anio");
    String cadena= dia+" - "+ mes + " - "+ anio;

    BDSQLite bd= new BDSQLite(getApplicationContext(), "eventos", null,1);
    db= bd.getReadableDatabase();

    String sql="select * from eventos where fechadesde='"+cadena+"'";
    Cursor c;



    String nombreEvento,fechadesde,horadesde,fechahasta,horahasta,descripcion,ubicacion;
    try {
        c=db.rawQuery(sql,null);
        arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        if(c==null||c.getCount()==0) {
            Toast.makeText(getBaseContext(), "No hay eventos disponibles", Toast.LENGTH_LONG).show();
        }




        if(c.moveToFirst()){
            do {
                nombreEvento=c.getString(1);
                ubicacion=c.getString(2);
                fechadesde=c.getString(3);
                horadesde=c.getString(4);
                fechahasta=c.getString(5);
                horahasta=c.getString(6);
                descripcion=c.getString(7);
                arrayAdapter.add(nombreEvento+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);
            } while(c.moveToNext());
            listView.setAdapter(arrayAdapter);
        }

    }catch (Exception ex) {
        Toast.makeText(getApplication(), "Error: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
        this.finish();

    }


}



private  void  eliminar(String dato){
    String []datos= dato.split(", ");

    String sql="delete from eventos where nombreEvento='"+datos[0]+"' and" +
            " ubicacion='"+datos[1]+"' and fechadesde='"+datos[2]+"' and " +
            "horadesde='"+datos[3]+"' and fechahasta='"+datos[4]+"' and horahasta='"+datos[5]+"' and descripcion='"+datos[6] + " '; ";
    try {

        arrayAdapter.remove(dato);         //eliminar del menú
        listView.setAdapter(arrayAdapter);
        db.execSQL(sql);


        Toast.makeText(getApplication(),"Evento eliminado",Toast.LENGTH_SHORT).show();
    }catch (Exception ex){
        Toast.makeText(getApplication(),"Error:"+ ex.getMessage(), Toast.LENGTH_SHORT).show();
    }

}

@Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, int i, long l) {
    AlertDialog.Builder builder= new AlertDialog.Builder(this);
    CharSequence []items= new CharSequence[2];
    items[0]="Eliminar Evento";
    items[1]="Cancelar";
    builder.setTitle("Eliminar evento")
            .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    if(i==0){
                        //eliminar evento
                        eliminar(adapterView.getItemAtPosition(i).toString());
                    }
                }
            });

    AlertDialog dialog= builder.create();
    dialog.show();
    return false;
}

Add events:

public class AddActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText nombreEvento, ubicacion, fechadesde, horadesde, fechahasta, horahasta;
    private EditText descripcion;

    private Button guardar, cancelar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        nombreEvento = (EditText) findViewById(R.id.edtNombreEvento);
        ubicacion = (EditText) findViewById(R.id.edtUbicacion);
        fechadesde = (EditText) findViewById(R.id.edtFechaDesde);
        fechahasta = (EditText) findViewById(R.id.edtFechaHasta);
        horadesde = (EditText) findViewById(R.id.edtHorainicio);
        horahasta = (EditText) findViewById(R.id.edtHoraHasta);
        descripcion = (EditText) findViewById(R.id.edtDescripcion);

        Bundle bundle = getIntent().getExtras();
        int dia = 0, mes = 0, anio = 0;

        dia=bundle.getInt("dia");
        mes=bundle.getInt("mes");
        anio=bundle.getInt("anio");


        fechadesde.setText(dia + " - " + mes + " - " + anio);
        fechahasta.setText(dia + " - " + mes + " - " + anio);

        guardar = (Button) findViewById(R.id.btnguardar);
        cancelar = (Button) findViewById(R.id.btncancelar);
        guardar.setOnClickListener(this);
        cancelar.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == guardar.getId()) {
            //guardar datos cajas de texto
            BDSQLite bd = new BDSQLite(getApplication(), "eventos", null, 1);
            SQLiteDatabase db = bd.getWritableDatabase();



            String sql = "insert into eventos" +
                    "(nombreEvento, ubicacion, fechadesde, horadesde, fechahasta, horahasta," +
                    "descripcion) values('" +
                    nombreEvento.getText()+
                    "','"+ ubicacion.getText()+
                    "','" +fechadesde.getText()+
                    "','" +horadesde.getText()+
                    "','"+fechahasta.getText()+
                    "','"+horahasta.getText()+
                    "','"+descripcion.getText();
            try {
                db.execSQL(sql);
                nombreEvento.setText("");
                ubicacion.setText("");
                fechadesde.setText("");
                fechahasta.setText("");
                horadesde.setText("");
                horahasta.setText("");
                descripcion.setText("");
                Toast.makeText(getBaseContext(), "Evento guardado", Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(getApplication(),"Error"+e.getMessage(),Toast.LENGTH_SHORT).show();

            }

        } else {
            this.finish();
            return;
        }
    }
}

BDSQLite:

public class BDSQLite extends SQLiteOpenHelper {

    private String sql = "create table eventos(" +
            "idEvento int identity,"+
            "nombreEvento varchar(40)," +
            "ubicacion varchar(60)," +
            "fechadesde date,"+
            "horadesde time,"+
            "fechahasta date,"+
            "horahasta time," +
            "descripcion varchar(60))";

    public BDSQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
  

ERROR:

     

java.lang.ArrayIndexOutOfBoundsException: length = 5; index = 5 caused by:   edit It should be noted that the error is generated in delete (String data)   which is in View events at the end. Thank you in advance.

    
asked by Nicolas Oporto 19.12.2017 в 09:15
source

2 answers

0

In this case you must ensure that the value of the string dato , always contains 7 values separated by "," , for example:

String dato = "valor1, valor2, valor3, valor4, valor5, valor6, valor7";

this so that when performing:

  String []datos = dato.split(", ");

and get the 7 elements of the array you need to build your query:

  String sql = "delete from eventos where nombreEvento='"+datos[0]+"' and" +
            " ubicacion='"+datos[1]+"' and fechadesde='"+datos[2]+"' and " +
            "horadesde='"+datos[3]+"' and fechahasta='"+datos[4]+"' and horahasta='"+datos[5]+"' and descripcion='"+datos[6] + " '; ";

otherwise, if it does not contain the 7 values, you will get the error:

  

java.lang.ArrayIndexOutOfBoundsException

    
answered by 19.12.2017 / 17:00
source
0

As it says @PabloLozano, the error occurs in that the array that is generated after calling the split function, has a size smaller than 7. This array is created from a String, which is generated in the following line of code inside the onItemLongClick method:

adapterView.getItemAtPosition(i).toString()

With the code you have given us, we can not know what objects you are recovering in that loop, but of course the toString method is not returning what you expect. You should make sure which class the object is returned with:

adapterView.getItemAtPosition(i)

Once you have clear what kind of object it is, you will see its toString () method, and there you will find the root of this problem.

We would lack that part of the code to be able to give a complete solution to this problem, but what I can do is to orientate you where you should look, and encourage you to fix it for yourself. If you still prefer to copy the class code, we can find what is causing the problem.

    
answered by 19.12.2017 в 13:21