How to pass listview item ID to ActionMode.Callback?

375 Views Asked by At

I am trying to delete a row from the database when I click on delete in Contextual action bar.But i am unable to get the id of the item which is long clicked.I have tried using setTag() to pass id, but it is force closing the app when the item is long clicked.

Here is my code:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            startActionMode(modeCallBack);
            mActionMode.setTag(id);
            view.setSelected(true);
            return true;
        }
    });

This is onActionItemClicked:

@Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.item_delete:
            Mydatabase.execSQL("delete from TableName where _id="
                    + mode.getTag());
            mode.finish();
            break;
        }
        return true;
    }
};
1

There are 1 best solutions below

0
On BEST ANSWER

If you have the items in an array and you long click on something the position that is passed into the

    public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long id)

Should be the index of the item in the array, assuming you have the ID stored in there you can rather simply pass that ID to an SQL query that would delete the item from your database.