I am new to programming and I have many doubts.
The first thing is that I'm doing a registry of people, I have the DB in sqlite, I have already managed to save, search and delete the information, this I show in a listview
, but when deleting several data the application stops, for example:
I have 3 records, I delete the first one and everything goes well, but I try to select the second one and it does not work anymore and the third one takes it as if it were the second one. I would really appreciate it if you could help me:)
private void consultar(){
DBHelper helper = new DBHelper(this,"Persona",null,1);
SQLiteDatabase db = helper.getReadableDatabase();
String sql = "select ID, nombre, direccion, telefono from Persona";
Cursor c = db.rawQuery(sql,null);
ArrayList<String> listado = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item, listado);
lista.setAdapter(adapter);
if(c.moveToFirst()){
do{
String linea = c.getInt(0)+" "+c.getString(1)+" "+c.getString(2)+" "+c.getString(3);
listado.add(linea);
}while(c.moveToNext());
}
db.close();
}
private void btnGuardar(String nombre, String direccion, String telefono){
DBHelper helper = new DBHelper(this,"Persona",null,1);
SQLiteDatabase db = helper.getWritableDatabase();
try
{
ContentValues c = new ContentValues();
c.put("nombre",nombre);
c.put("direccion",direccion);
c.put("telefono",telefono);
db.insert("Persona",null,c);
db.close();
Toast.makeText(this,"Registro insertado...",Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(this,"Error: "+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
private int buscarRegistro(int pos) {
pos++;
DBHelper helper = new DBHelper(this,"Persona",null,1);
SQLiteDatabase db = helper.getReadableDatabase();
String sql = "SELECT id, nombre, telefono, direccion from Persona WHERE ID="+ pos;
Cursor c = db.rawQuery(sql,null);
c.moveToFirst();
Nombre.setText(c.getString(1));
Direccion.setText(c.getString(2));
Telefono.setText(c.getString(3));
return pos;
}
private void eliminar(int pos) {
int posicion = pos;
DBHelper helper = new DBHelper(this, "Persona", null, 1);
SQLiteDatabase db = helper.getWritableDatabase();
try {
String sql = "DELETE FROM Persona WHERE id ="+posicion;
db.execSQL(sql);
db.close();
Toast.makeText(this, "Registro Eliminado", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(this, "Error: "+ e.getMessage(), Toast.LENGTH_SHORT).show();
}
}