Android - Listview删除项目和刷新

Par*_*ani 9 android android-listview

我正在尝试使用Delete功能实现ListView以从列表视图中删除项目.我成功删除但在删除数据库中的项目后无法刷新列表视图.

实际上,单击listitem,我显示AlertBox为"删除"和"取消"操作,单击"删除",项目应从数据库中删除,以及从列表视图和列表视图中删除应该刷新.我也用过notifyDataSetChanged()方法.

lview = (ListView) findViewById(R.id.lview);
adapter = new ListView_CustomAdapter(this, listitemDisplay);
lview.setAdapter(adapter);

lview.setOnItemClickListener(new OnItemClickListener() 
{
     @Override
     public void onItemClick(AdapterView<?> a, View v, int position, long id)
     {
        Show_Alert_box(v.getContext(),"Please select action.",position);
     }
});
Run Code Online (Sandbox Code Playgroud)

和Show_Alert_box的代码:

 public void Show_Alert_box(Context context, String message,int position)
     {
         final int pos = position;

         final AlertDialog alertDialog = new  AlertDialog.Builder(context).create();
            alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
            alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    try
                    {
                        db.open();
                                 String[] whereArgs={String.valueOf(pkID)};
        return db.delete(DATABASE_TABLE_4,"pk_pkID == ?",whereArgs);    
                        adapter.notifyDataSetChanged();
                        db.close();
                    }
                    catch(Exception e)
                    {

                    }
            } }); 
            alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    alertDialog.dismiss();
            } }); 

            alertDialog.setMessage(message);
            alertDialog.show();
     }
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 11

它是否从列表适配器中删除它?如果不是那就是notifyDataSetChanged()不会对你有好处的原因.

实际上再次查看你的代码我只能发现你从数据库中删除它而不是适配器本身.

编辑(回答评论):没有你的ListView_CustomAdapter课,这很难做到.问题是,在这个适配器中有一个数据集(你在构造函数(listitemDisplay)中放置的数据集)也需要更新.只有这样才有意义notifyDataSetChanged().


Par*_*han 9

再次使用Intent调用该Activity


Fel*_*ett 6

我猜这是用的

getActivity().recreate();
Run Code Online (Sandbox Code Playgroud)

而不是通过新的Intent重新启动活动更好,因为使用新的Intent只会停止当前活动而不会销毁它.

无论如何,它的工作原理.


Phy*_*Tea 5

如果你有光标,在调用notifyDataChanged()之前调用requery()