如何通过长按以及SQLite

时间:2015-12-12 19:14:46

标签: android sqlite listview

我想长时间点击列表视图(数据也来自SQLite),然后出现删除弹出菜单。当我单击删除弹出菜单时,列表视图中的选定行将与数据库一起删除。

view_lv_diary_info.setOnItemLongClickListener(new OnItemLongClickListener(){

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

            PopupMenu p = new PopupMenu(ViewDiaryActivity.this, view);
            p.getMenuInflater().inflate(R.menu.main_popup_menu, p.getMenu());
            p.show();

            return true;
        }           
    });

onDelete方法:

public void doDelete(MenuItem mi) {

        /* db.delete(DiaryEntry.TABLE_NAME,
                ??,
                ??);
        */
        Toast.makeText(this, "Record deleted.", Toast.LENGTH_SHORT).show();
    }

我尝试了这段代码,吐司出现了。但我不知道SQL语句。

谢谢:)

1 个答案:

答案 0 :(得分:0)

你可以这样做:

  listViewEdit.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  public boolean onItemLongClick(final AdapterView<?> p, View v, final int po, long id) {
               AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
               builder.setTitle("Delete");
               builder.setMessage("Are you sure you want to delete?");
               builder.setIcon(android.R.drawable.ic_dialog_alert);
               builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int ii) {
                    database = dbHelper.getWritableDatabase();
                    Cursor cursor = (Cursor) p.getItemAtPosition(po);
                   // Get the state's capital from this listview_item_row in the database.
                    long ID = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
                    sqlcon.delete(ID); // sqlcon is one my class, InfoAPI object
                    Cursor cursor2 = sqlcon.readName();
                    dataAdapter.changeCursor(cursor2);
                    }
                });

                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
                    {
                       public void onClick(DialogInterface dialog, int ii) {
                       dialog.dismiss();
                     }
                        }
                  );
                builder.show();
                return true;
            }
        });

<强> InfoAPI

 public void delete(long a)   // delete the selected row data 
    {
        database.delete(MyDatabaseHelper.TABLE_INFO, MyDatabaseHelper.ID + " =?", new String[] { a + "" });
    }