I can not get the cursor to read what the SQL statement returns- Android Studio

1

I am creating a calendar-type app and when I run the app and I give it the option to see events I get an error in the cursor: The error is as follows " Could not read row 0, col 1 from CursorWindow Make sure the Cursor is initialized correctly before accessing data from it. "

I put the project codes below: In this one just call the following activities

import android.content.DialogInterface;
    import android.content.Intent;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.CalendarView;
    import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements  
CalendarView.OnDateChangeListener{


private CalendarView calendarview;

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

    calendarview= findViewById(R.id.calendarView);
    calendarview.setOnDateChangeListener(this);
}
// este método saltara cuando se cambie las fechas en el calendario
@Override
public void onSelectedDayChange(CalendarView view, int i, int i1, int i2) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    CharSequence [] items = new CharSequence[3]; //contenerá las opciones 
que podrá escoger el usuario
    items[0]= "Agregar eventos";
    items[1]="Ver eventos";
    items[2]="Cancelar";

    final int dia,mes,anio;
    dia=i2;
    mes=i1+1;// esto es por que el més empieza en cero y de esta manera se evita eso
    anio=i;


    //Le ponemos título a la alerta y le ponemos las opciones más un 
escuchador de cuando presione dichas opciones
    builder.setTitle("Seleccione una opción")
            .setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    //comparamos la opción seleccionada
                    if (i==0){
                        //actividad agregar eventos
                        Intent intent=new Intent( getApplicationContext(), 
AddActivity.class);
                        Toast.makeText(getApplication(),"dia "+dia+" ,Mes 
"+mes+", AÑO "+anio, Toast.LENGTH_LONG).show();
                        intent.putExtra("dia",dia);
                        intent.putExtra("mes",mes);
                        intent.putExtra("anio",anio);
                        startActivity(intent);

                    }else if (i==1){
                        //ver actividad eventos
                        Intent intent=new Intent( getApplicationContext(), ViewEventsActivity.class);
                        intent.putExtra("dia",dia);
                        intent.putExtra("mes",mes);
                        intent.putExtra("anio",anio);
                        startActivity(intent);
                    }else{
                        //selecciona cancelar y salimos del método
                        return;
                    }
                }
            });

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

This is the add events:

    import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddActivity extends AppCompatActivity implements View.OnClickListener {

private EditText nombreEvento;
private EditText ubicacion;
private EditText fechaDesde;
private EditText horaDesde;
private EditText fechaHasta;
private EditText horaHasta;
private EditText descripcion;
private Button guardar, cancelar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add);
    nombreEvento= findViewById(R.id.edtNombreEvento);
    ubicacion=findViewById(R.id.edtUbicacion);
    fechaDesde=findViewById(R.id.edtFechaDesde);
    fechaHasta=findViewById(R.id.edtFechaHasta);
    horaDesde=findViewById(R.id.edtHoraInicio);
    horaHasta=findViewById(R.id.edtHoraHasta);
    descripcion=findViewById(R.id.edtDescripcion);

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

    Toast.makeText(getApplication(),"dia "+dia+" ,Mes "+mes+", AÑO "+anio, 
Toast.LENGTH_LONG).show();
    fechaDesde.setText(dia+"-"+mes+"-"+ anio);
    fechaHasta.setText(dia+"-"+mes+"-"+ anio);

    guardar=findViewById(R.id.btnGuardar);
    cancelar= findViewById(R.id.btnCancelar);

    guardar.setOnClickListener(this);
    cancelar.setOnClickListener(this);

}

@Override
public void onClick(View view) {
    //comparamos la opción presionada
    if(view.getId()==guardar.getId()){
        //guardar los datos de las caja de texto
        BDSQLite bd = new BDSQLite(getApplication(), "Agenda",null,1);
        SQLiteDatabase db= bd.getWritableDatabase(); //Le asignamos los 
datos en modo String para guardarlos

        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("");
            horaDesde.setText("");
            fechaHasta.setText("");
            horaHasta.setText("");
            descripcion.setText("");
        }catch (Exception e){
            Toast.makeText(getApplication(),"Error"+e.getMessage(), 
Toast.LENGTH_SHORT).show();
        }

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

This activity shows the events HERE GIVES ME ERROR :

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class ViewEventsActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener{

    //Declaramos un array el cual uaremos para leer los datos de la base de datos
    private SQLiteDatabase db;
    private ListView listView;
    private ArrayAdapter<String >arrayAdapter;


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

        listView=findViewById(R.id.ltvListaEventos);
        //nos sirve para cuando se mantiene presionado un item en la lista y para borrar elementos
        listView.setOnItemLongClickListener(this);


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

        //metemos los valores en un String para poder validar los datos en la BBDD
        String cadena= anio+ " - " +mes+ " - " +dia;

        //conectamos a nuestra BBDD en modo lectura
        BDSQLite bd= new BDSQLite(getApplicationContext(),"Agenda",null,1);
        db = bd.getReadableDatabase();//modo lectura
        String sql=" select count(*) from eventos";
        //delcaramos una variable de tipod Cursor que nos servira para guardar los registros que nos devuelva la consulta
        Cursor c;
        //declaramos variables temporales para almacenar los datos temporalmente
        String nombre, fechadesde,fechahasta,descripcion,ubicacion;
        try{
            //los registros que nos devuelva los guardamos  en c
            c= db.rawQuery(sql,null);//****NO ME LEE NADA****
            Toast.makeText(getApplication(),String.valueOf(c.getCount()), Toast.LENGTH_LONG).show();
            //Log.i("Count",String.valueOf(c.getCount()));

            //instanciamos el arrayAdapter
            arrayAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
            //comparamos que haya datos para leer
            if(c!=null){
                c.moveToFirst();

                do{
                    String ident= c.getString(0);
                    nombre=c.getString(1);
                    ubicacion=c.getString(2);
                    fechadesde=c.getString(3);
                    fechahasta=c.getString(5);
                    descripcion=c.getString(7);

                    arrayAdapter.add("id"+ident+","+nombre+", "+ubicacion+", "+fechadesde+", "+fechahasta+", "+descripcion);
                }while (c.moveToNext());
                listView.setAdapter(arrayAdapter);

            }else{
            //si no hay datos en el cursor no mostramos la interfaz
            this.finish();
        }

        }catch (Exception e){
            Toast.makeText(getApplication(),"Error eeeeeeeeee    "+e.getMessage(), Toast.LENGTH_LONG).show();
            //si ocurre algun error cierra la interfaz
            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 fechahasta='"+datos[3]+"' and descripcion='"+datos[4]+"'";
        try {
            arrayAdapter.remove(dato);
            listView.setAdapter(arrayAdapter);
            db.execSQL(sql);
            Toast.makeText(getApplication(),"Evento eliminado", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(getApplication(),"Error"+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onItemLongClick(final AdapterView<?> adapterView, View view, int position, long id) {
//agregamos un dialogo para que el usuario pueda eliminar el evento
        AlertDialog.Builder builder= new AlertDialog.Builder(this);
        CharSequence[] items = new CharSequence[1];
        items[0]="Eliminar eventos";
        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
                            //le pasamos el dato que selecciona el usuario
                            eliminar(adapterView.getItemAtPosition(i).toString());
                        }
                    }
                });
        AlertDialog dialog =builder.create();
        dialog.show();
        return false;
    }
}

Finally I leave the database:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class BDSQLite extends SQLiteOpenHelper {
    private String sql = "create table eventos(" +
            "idEvento integer primary key AUTOINCREMENT," +
            "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 sqLiteDatabase) {
        sqLiteDatabase.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
    
asked by Hello There 02.01.2019 в 17:56
source

1 answer

0

The error message indicates that you can not read the item in the cursor

  

Could not read row 0, col 1 from CursorWindow. Make sure the Cursor is   initialized correctly before accessing data from it.

I suggest you review these points that may cause the problem you are presenting:

  • It is important that you review the query since it probably does not get results or your table is empty.

In this case you are using the count () function which is a cause of the problem:

String sql=" select count(*) from eventos";

change to:

String sql=" select * from eventos";
  • Remember that if you did tests to build the database, there may be the possibility of having an incorrect structure, for this you delete the application and upload it back to your device.
  • Always remember to close the cursors when you finish obtaining the data, for this use the .close() method.

I suggest you change the reading of your cursor data:

 if(c!=null){
                c.moveToFirst();

                do{
                    String ident= c.getString(0);
                    nombre=c.getString(1);
                    ubicacion=c.getString(2);
                    fechadesde=c.getString(3);
                    fechahasta=c.getString(5);
                    descripcion=c.getString(7);

                    arrayAdapter.add("id"+ident+","+nombre+", "+ubicacion+", "+fechadesde+", "+fechahasta+", "+descripcion);
                }while (c.moveToNext());
                listView.setAdapter(arrayAdapter);

            }else{
            //si no hay datos en el cursor no mostramos la interfaz
            this.finish();
        }

to this form, where the cursor is closed:

 if(c!=null){
            while (c.moveToNext()) {
                String ident= c.getString(0);
                nombre=c.getString(1);
                ubicacion=c.getString(2);
                fechadesde=c.getString(3);
                fechahasta=c.getString(5);
                descripcion=c.getString(7);

                arrayAdapter.add("id"+ident+","+nombre+", "+ubicacion+", "+fechadesde+", "+fechahasta+", "+descripcion);
            }
            //Cierra cursor.
            c.close();
            listView.setAdapter(arrayAdapter);

        }else{
        //si no hay datos en el cursor no mostramos la interfaz
        this.finish();
    }
    
answered by 07.01.2019 / 07:51
source