错误java.lang.ArrayIndexOutOfBoundsException:length = 5;指数= 5

时间:2017-12-19 05:48:00

标签: java android arraylist android-sqlite

我正在为我的大学(应用程序日历等)工作 Android Studio Project ,其中一项功能是在日历的某一天触摸(CalendarView) ,显示添加事件的布局,稍后将事件保存在SQLITE中,(在另一个活动中显示事件列表的位置)问题是当我想删除事件时java.lang.ArrayIndexOutOfBoundsException: length=5; index=5 )。 在Viewevents中,erasear(String dato)是错误的代码,如何解决问题?感谢。

查看活动:

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 nombre,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 {
                nombre=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(nombre+", "+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;
}

}

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

}

ERROR:

java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.example.niikoo.fondocelular.ViewEventsActivity.eliminar(ViewEventsActivity.java:87)
at com.example.niikoo.fondocelular.ViewEventsActivity.access$000(ViewEventsActivity.java:17)
at com.example.niikoo.fondocelular.ViewEventsActivity$1.onClick(ViewEventsActivity.java:116)

编辑:具有sql和datos结构的代码,我如何修复错误:(

3 个答案:

答案 0 :(得分:2)

异常行(java.lang.ArrayIndexOutOfBoundsException: length=5; index=5)明确提到您正在尝试获取index=5,但dato的长度为5length=5)。

因此,只使用适当的索引,即索引0 to 4 OR 确保有足够的indexes可供访问。

注意:您已使用dato.split(", ");。试试dato.split(",");。问题在于分裂器的模式。

答案 1 :(得分:1)

看起来你用逗号分割成数组的String dato可能不是你想的长度。错误显示数组中有5个项目,因此在这种情况下您可以访问的最大索引是datos[4],因为数组是从0开始的。

拆分后调试数组:

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

答案 2 :(得分:0)

检查此方法的输入,它不在代码中。

eliminar(adapterView.getItemAtPosition(i).toString());

发生错误是因为分割String后得到的数组只有5个元素(4个逗号):

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

然后你尝试从该数组中获取第6个(索引5)和第7个(索引6)元素:

datos[5]+"' and descripcion='"+datos[6];

没有这样的元素,因此您会收到此ArrayIndexOutOfBoundsException错误。

要修复,请尝试查找 adapterView 的输入。

编辑:在此行 2个字符串似乎为空

arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);

因此,当你得到一个&#34;,&#34;并将其拆分(&#34;,&#34;)它不会计算&#34;&#34;字符串,您在结果数组中获得的项目更少,从而导致错误。