0

Ok, so I'm trying to delete elements from a ListView, and everything goes alright until I try to delete the last element, but only if I delete the second last element and the try to delete the last one. Here's my code:

public class TestActivity extends ListActivity {

ListView list;
PAdapter adapter;
static SQLiteDatabase db;
static ArrayList<Profesor> datos;

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

db = openOrCreateDatabase("DBLogin", MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS Profesor (Id integer primary key AUTOINCREMENT"
            + ", Nombre" + " varchar(30), Imagen varchar(15), Fecha" + " varchar(15)" +
            ", Direccion varchar(35), sexo varchar(10), Telefono varchar(15), creado int);");

    list = (ListView) findViewById(android.R.id.list);

    datos = new ArrayList<Profesor>();

    datos = datos();
    adapter = new PAdapter(this, R.layout.row, datos);

    setListAdapter(adapter);



list.setOnItemLongClickListener(new OnItemLongClickListener(){

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            if (datos.get(arg2).getCreado() == 1) {
                PopupMenu popup = new PopupMenu(TestActivity.this, list);
                popup.getMenuInflater().inflate(R.menu.popup3, popup.getMenu());
                final int id = arg2;
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        delete(datos.get((int)adapter.getItemId(id)));
                        datos = datos();
                        adapter = new PAdapter(TestActivity.this, R.layout.row, datos);
                        setListAdapter(adapter);
                        list.invalidateViews();
                        return true;
                    }
                });

                popup.show();
            }
            return false;
        }
    });
}


private ArrayList<Profesor> datos(){
    ArrayList<Profesor> ap = new ArrayList<Profesor>();
    Cursor cursor = db.rawQuery("SELECT * FROM Profesor", null);
    if(cursor.moveToFirst()){
        do {
            Profesor p = new Profesor(null, null);
            p.setId(cursor.getInt(0));
            p.setNombre(cursor.getString(1));
            p.setFecha(cursor.getString(3));
            p.setDireccion(cursor.getString(4));
            p.setSexo(cursor.getString(5));
            p.setImagen(cursor.getString(2));
            p.setCreado(cursor.getInt(7));
            p.setTelefono(cursor.getString(6));
            ap.add(p);
        } while(cursor.moveToNext());
    }
    return ap;
}

public static void delete(Profesor p){
    db.execSQL("DELETE FROM Profesor WHERE Id = " + p.getId() + ";");
}

Here is the class PAdapter:

public class PAdapter extends ArrayAdapter<Profesor> {

private Context context;
private int layout;
private ArrayList<Profesor> datos;

public PAdapter(Context context, int layout, ArrayList<Profesor> datos) {
    super(context, layout, datos);
    this.context = context;
    this.layout = layout;
    this.datos = datos;
}

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View item = inflater.inflate(layout, parent, false);

    ImageView imagen = (ImageView) item.findViewById(R.id.imageView1);
    datos.get(position).imagen(imagen, context, false);


    TextView nombre = (TextView) item.findViewById(R.id.tNombre);
    nombre.setText(datos.get(position).getNombre());


    return item;
}

}

Funny thing is, it executes the code following the delete but doesn't delete the last element, neither does it throw me an exception. And again, it only happens with the last element, and only after I delete the one before it, if I close and reopen the app afterwards I can delete it normally.

Jairo
  • 306
  • 3
  • 12
  • Check : http://stackoverflow.com/questions/26623385/how-can-i-delete-my-list-row-by-clicking-on-button-in-each-row-of-the-listview/26623451#26623451 – Haresh Chhelana Nov 08 '14 at 09:30

4 Answers4

0

I assumed you passed pos = 3 as parameter value. Because the size of list is 3, last element's position should be 2.

*EDIT:

Remember, start index of listview and adapter is different. The ListView item pos starts from "1" as first position, adapter (such as array) starts from index "0" as first position.

adapter.remove(adapter.getItem(pos-1)); 
raj
  • 2,088
  • 14
  • 23
  • I'm pretty sure the item position starts at 0 too, I've used similar code and it's worked flawlesly, besides it wouldn't delete the element you select were it the case. Also I think it would give an ArrayIndexOutOfBoundsException or something like that. – Jairo Nov 10 '14 at 06:15
0

You have some mistakes in your code. My following suggestion dont promise will solve your current problem, but lets try it :

  1. Pay attention when you setting the adapter setListAdapter(adapter);, the list will set its adapter each time user did onClick - which is a waste.Use adapter.add()/adapter.remove() instead of reset all data by doing setListAdapter again and again.
  2. You called list.invalidateViews(), for what? In your case, adapter.notifyDataSetChanged() is enough.
Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
  • Thanks for the advice, I'll keep it in mind. But the main issue is deleting the last element from de DB, it only works sometimes and works perfectly with all other elements. – Jairo Nov 10 '14 at 06:16
0

Try this:It's working fine for me.

    ListView list;
    adapter = new MyListAdapter(this);
    list = (ListView) findViewById(android.R.id.list);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
        adb.setTitle("Delete?");
        adb.setMessage("Are you sure you want to delete " + position);
        final int positionToRemove = position;
        adb.setNegativeButton("Cancel", null);
        adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                MyDataObject.remove(positionToRemove);
                adapter.notifyDataSetChanged();
            }});
        adb.show();
        }
    });
vijay
  • 1,475
  • 2
  • 16
  • 26
  • Thing is I need to delete it from the database too and it's failing to do so, but only with the last element, and not always. I was hoping any of you could help me as to what is wrong with my code. – Jairo Nov 10 '14 at 06:11
0

I solved it by Adding this in the activity of the single item so if i get back to the ListView Activity it is refreshed because of finish(); function.[ 8 feb 2020]

@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(SingleItem.this, ListView.class));
    finish();
}