Search code examples
androidsqlitecursorandroid-cursoradapter

I want to delete a row in a listview using a button in that row without cursor.requery as it is depreciated


I am using a CursorAdapter with 3 TextViews and 1 button. I want to delete the entry from my database when I hit the button.
Note: There exists many posts on this, however they all suggest the same code using the now depreciated "cursor.requery"

@Override
public void bindView(View view, final Context context, final Cursor cursor) {

    TextView viewID = (TextView) view.findViewById(R.id.viewID);
    TextView viewAmount=(TextView) view.findViewById(R.id.viewAmount);
    TextView viewCategory=(TextView) view.findViewById(R.id.viewCategory);
    Button buttonDelete = (Button) view.findViewById(R.id.buttonDelete);

    final int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
    String amount = cursor.getString(cursor.getColumnIndexOrThrow("amount"));
    String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));

    viewID.setText(String.valueOf(id));
    viewAmount.setText(amount);
    viewCategory.setText(category);

    buttonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {
                Toast.makeText(context, "Deleted item " + id, Toast.LENGTH_SHORT).show();
            //Do I create a DB handler here and run a dbHandler.deleteItem(id)   
            //method or do something else?    

            }
        });

    }

Solution

  • try this one

    buttonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {
                Toast.makeText(context, "Deleted item " + id, Toast.LENGTH_SHORT).show();
                String query = "DELETE * from *table_name* where _id = "+ id + "";
                db.execQuery(query) // db is your DatabaseHelper  
                startActivity(getIntent()); 
                finish();                
            }
        });
    
    }