-2

I have a table address (id,name,phone,address). I expose the details (name,phone,address) in a list view.

I am adding a onCLick function for each row in the list to delete it. How to delete only that row when we do not have the primary_key with us. i.e we have only (name,phone,address) with us. There may be duplicate rows, so do not want to delete multiple rows.

If I give delete from address where name ='name_val' and phone = 'phone_val' and address='address_val', it will delete all the rows that match the condition which I do not intend to do.

The DB code.

public List<String> getAllRecords(){

    String query = "Select  * FROM "+ TABLE_ACT;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(query,null);

    List activities = new ArrayList<String>();
    if(c.moveToFirst()){
        do{
            String actData= c.getString(1)+"\n"+c.getString(2)+"\n"+c.getString(3);
            //getString(1) is name, getString(2) is phone, getString(3) is address
            activities.add(actData);
        }while(c.moveToNext());
    }

    c.close();
    db.close();

    return activities;
}

Above method returns a list of Strings.This is used in the activity as shown below.

lists = dbHandler.getAllRecords();
ListAdapter adapter = new ArrayAdapter<String(this,android.R.layout.simple_list_item_1,lists);

and it has onItemClickListener that is inherited from ListActivity.

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Log.e("Hello", "You clicked Item: " + id + " at position:" + position);


    }

Kindly help me delete a particular row given that only Name,phone and address is present in ListItem.

CS_noob
  • 557
  • 1
  • 6
  • 18

2 Answers2

2
public void deleteItem(String get_ID)
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM Table_Name WHERE TABLE_ID='"+get_ID+"'");
}

OnClick Method

viewOBJ.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

          myDbOBJ = new Your_Data_Base_Class(getContext());
                  myDbOBJ.deleteItem("1"); // set Dynamic
                  notifyDataSetChanged();
        }
      });

NOTE

get_ID will be String or Integer. For best approach TABLE_ID should be Primary Key .

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

Just use the id from the selected row:

delete from address
where id = id_val

If you are using a CursorAdapter as you should, then you can call getItemId():

long id = getItemId(position);
String where = "id=?";
String whereArgs = { Long.toString(id) };
db.delete(tableName, where, whereArgs);

This can go directly in your OnClickListener or in your database helper. Note that I assume you already have an open SQLiteDatabase object. If not, you will have to open one.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268