0

What i want is when the user clic on contact a context Menu appear with item "delete" so i did this, but the problem is I want that when he clic on delete a row from Sqlit ( that corresponds to the contact I just clicked) Activity.class

 @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);

}


@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int i = info.position;
    switch (item.getItemId()) {
        case R.id.delete:

            dbHandler.deleteEtudiant(i);
            Toast.makeText(this,"deleted   "+i, Toast.LENGTH_SHORT).show();
           return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

MyDBHandler.class

 public void deleteEtudiant(int i)
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete("etudiant", "Id+ =" + i, null);
}

1 Answers1

0

The problem with your code is that your are getting the id of "AdapterContextMenuInfo" object and sending it to the database "delete()" method. But actually you need to send the id of the of the item of database, the value that is stored in "ID" column of that particular row in SQlite Database.

Please have a look on the tutorial given below, specially check the "getContact()" and "deleteContact()" method of the tutorial.

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Zohaib Hassan
  • 984
  • 2
  • 7
  • 11
  • i'm gonna check this tuto ! thanx but how can i get the id of the element on which I just clicked ? – kahina kahina May 09 '17 at 22:46
  • To get the id, first you have to get the item. You must have given an array to your adapter. You have to get the position from adapter and get the specific row from array on that specific position. Now you can get the id from that row. – Zohaib Hassan May 09 '17 at 22:52
  • how can i do that ? – kahina kahina May 09 '17 at 23:00
  • I am not sure about what you have done in your code. But I hope these links will help you. http://stackoverflow.com/questions/2321332/detecting-which-selected-item-in-a-listview-spawned-the-contextmenu-android – Zohaib Hassan May 09 '17 at 23:09
  • http://stackoverflow.com/questions/2453620/android-how-to-find-the-position-clicked-from-the-context-menu – Zohaib Hassan May 09 '17 at 23:09
  • You must have used an "Adapter" to set the data on listview. Declare that adapter globally then you can get your item from that adapter in "onContextItemSelected()" method like this: YourRowClass item = yourAdapter.getItem(info.position); And to get the "ID" use: dbHandler.deleteEtudiant(item.getId()); – Zohaib Hassan May 10 '17 at 21:00