Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误java.lang.ArrayIndexOutOfBoundsException:长度=5;指数=5_Java_Android_Arraylist_Android Sqlite - Fatal编程技术网

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

错误java.lang.ArrayIndexOutOfBoundsException:长度=5;指数=5,java,android,arraylist,android-sqlite,Java,Android,Arraylist,Android Sqlite,我正在为我的大学做Android Studio项目(应用程序日历和更多),其中一项功能是在日历的一天中触摸(CalendarView),显示添加事件的布局,然后将事件保存在SQLITE,(在另一个活动中显示事件列表)问题是当我想删除事件时(java.lang.ArrayIndexOutOfBoundsException:length=5;index=5)。 在Viewevents eliminar(String dato)中,如果代码有错误,如何修复该问题?谢谢 查看事件: public cla

我正在为我的大学做Android Studio项目(应用程序日历和更多),其中一项功能是在日历的一天中触摸(
CalendarView
),显示添加事件的布局,然后将事件保存在
SQLITE
,(在另一个活动中显示事件列表)问题是当我想删除事件时(
java.lang.ArrayIndexOutOfBoundsException:length=5;index=5
)。 在Viewevents eliminar(
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;
}
添加事件活动

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

错误:

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和dato结构的代码,我如何修复错误:(

看起来你用逗号将
字符串dato
拆分为一个数组可能不是你想象的长度。错误显示数组中有5个项目,因此在这种情况下,你可以访问的最大索引是
dato[4]
因为数组是基于0的

拆分后调试阵列:

String []datos= dato.split(", ");
异常行
(java.lang.ArrayIndexOutOfBoundsException:length=5;index=5)
清楚地提到您正在尝试获取
index=5
,但是
dato
的长度是
5
length=5

因此,只使用适当的索引,即索引
0到4
确保有足够的
索引可访问


注意:您使用了
dato.split(“,”);
。尝试使用
dato.split(“,”);
。可能是拆分器的模式有问题。

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

eliminar(adapterView.getItemAtPosition(i).toString());
出现此错误的原因是,拆分字符串后得到的数组只有5个元素(4个逗号):

但是,您尝试从该数组中获取第6个(索引5)和第7个(索引6)元素:

datos[5]+"' and descripcion='"+datos[6];
没有这样的元素,因此您会得到此
ArrayIndexOutOfBoundsException
错误

要修复此问题,请尝试查找适配器视图的输入

编辑:在这一行中,有两个字符串显示为空:

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

因此,当您得到一个“,”并用split(,”)拆分它时,它不会计算“”字符串,并且在结果数组中得到的项目较少,这导致了错误。

dato的长度是多少?
,因为错误表明您试图使用不存在的数组元素,即数组超出范围检查dato[6]如果它存在或没有错误,则表示您拥有大小为5的数组。这意味着您只能从该数组中从索引0到4获取数据。上面的任何内容都将引发ArrayoutOfBoundsCeption。是在sql中定义的。我想,我不知道如何解决此问题:/i知道,但我不知道如何解决此问题,代码包含有关如何创建的所有信息编辑方法:(在上一次编辑中,我把结构放在ArrayAdapter.add中,我把用“,”分隔的句子放在上面,我如何修复错误:(,我只发布了所有代码eliminar(字符串dato),有错误如果我改为(,”),这将出现在AVD中,PS:我如何看到dato中的文本?[1]:我修复了SQL查询,错误仍然出现:(,我是如何看待datos中的文本的???@NicolasOporto你确定这里更新了相同的代码吗。因为有足够的机会打字,我该怎么办?:(我不知道为什么有5个元素以及为什么存在错误,在上次编辑中,我正确地放置了代码,如果你能告诉我如何解决问题:(感谢Viewevents arrayAdapter.add中的输入,请帮助我了解如何查看datos?中的文本,或查看数组中未显示的元素??感谢必须调试应用程序,使用LogCat查看哪些项为空,并跟踪它们以找到问题的根源。我已经告诉您了我能告诉您的一切。
datos[5]+"' and descripcion='"+datos[6];
arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);