【问题标题】:How to delete items from listview created from SQLite using OnItemLongClickListener()?如何从使用 OnItemLongClickListener() 的 SQLite 创建的列表视图中删除项目?
【发布时间】:2016-02-01 15:48:02
【问题描述】:

我在使用 SimpleCursorAdapter 创建的列表视图中找不到要删除的答案 所以我在一个片段中制作这个列表视图,这是代码

final Cursor cursor = myDb.cautarevenituri();

    // The desired columns to be bound
    final String[] columns = new String[] {
            DatabaseHelper.COL_2,
            DatabaseHelper.COL_3
    };

    int[] toviewids = new int[] { R.id.nume_item,R.id.valoare_item};
    dataAdapter = new SimpleCursorAdapter(getActivity().getBaseContext(),R.layout.item_layout,cursor,columns,toviewids,0);
    //
    final ListView listView = (ListView)getView().findViewById(R.id.listView_venituri);

    listView.setAdapter(dataAdapter);
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long arg3) {
            Toast.makeText(getActivity(), " " + position, Toast.LENGTH_LONG).show();

            //delete from listview in database and listview too??
            //
            //

            return false;
        }

    });

谢谢。

【问题讨论】:

    标签: java android sqlite listview simplecursoradapter


    【解决方案1】:

    从数据库中删除并刷新列表视图。

    【讨论】:

      【解决方案2】:

      您必须更新您传递给适配器的列表,然后调用adapter.notifyDataSetChanged()

      【讨论】:

      • 问题是如何更新呢?我不能使用 dataAdapter.add()
      • 你可以使用 notifyDataSetChange() 或者像你一样重新设置适配器listView.setAdapter(dataAdapter);
      • 如何更改适配器,我无法更改 SimpleCursorAdapter
      • 您可以使用您更新的新列表声明一个 newAdapter,然后设置适配器。但是正确的方法是制作一个自定义适配器,然后刷新列表。列出这个stackoverflow.com/questions/18395753/…
      【解决方案3】:

      使用swapCursor() 方法更新SimpleCursorAdapter 内的数据:

      myDb.getWriteableDatabase().delete(TABLE_NAME, KEY_ID + "=?", position);
      Cursor newCursor = myDb.getReadableDatabase().query(**etc.**);
      dataAdapter.swapCursor(newCursor);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多