Utman Alami
Utman Alami

Reputation: 131

delete item issue from listview

i have a list view filled with data coming from database, i want when i click on an item to

disappear, i used --list.remove(position)-- but i have an error add cast to list.

HERE the list view :

    private void populateListViewFromDB() {
    Cursor cursor = db.getAllRecords();
    startManagingCursor(cursor);
    String[] databaseColumnNames = new String[] { DBAdapter.col_Region };
    int[] toViewIDs = new int[] { android.R.id.text1, android.R.id.text2 };

    SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_expandable_list_item_1, cursor,
            databaseColumnNames, toViewIDs, FLAG_REGISTER_CONTENT_OBSERVER);

    final ListView list = (ListView) findViewById(android.R.id.list);
    list.setAdapter(myCursordapter);

HERE my code when i want to delete an item :

   list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(final AdapterView<?> arg0, View arg1,
                final int position, long arg3) {
                 list.remove(position); 
             adapter.notifyDataSetChanged();}

Upvotes: 0

Views: 57

Answers (1)

Aleksey
Aleksey

Reputation: 239

There is no ListView.remove() method. You should remove correspondent item from the data model and then refresh your adapter.

In your OnItemClickListener listener get the bound data item:

Object itemObj = adapter.getItem(position);

Then, delete this item from your DB.

Then get new instance of your cursor and update your cursor adapter:

if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD){
    adapter.swapCursor(newCurosr);
} else {
    adapter.changeCursor(newCursor);
}

Then, notify your list view about data changes:

adapter.notifyDataSetChanged();

Upvotes: 1

Related Questions