java - SQLite ID 列和 onItemLongClick

标签 java android sqlite android-studio

我一直在寻找没有运气,这是我的代码

// Product List
    public void setProductList() {

        productDB = new DatabaseHelper(this);
        listView = (ListView) findViewById(R.id.list);
        listAdapter = listView.getAdapter();


        Cursor prodView = productDB.getAllData();
        prodView.moveToFirst();
        ArrayAdapter<String> listAdaptor = new ArrayAdapter<String>(this, R.layout.medicinelistmenu, R.id.productlistsTextView1);

        while (prodView.moveToNext()) {
            listAdaptor.add(prodView.getString(1));
            
        }

        listView.setAdapter(listAdaptor);


        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {

                productDB.deleteProduct(id);
                Toast.makeText(medicineList.this, "Item Deleted", Toast.LENGTH_LONG).show();
                finish();
                startActivity(getIntent());

                return true;
            }

        });
    }

使用 onItemLongClick 函数,其他帖子告诉我 AdapterView 中的 long 值将是 SQLLite ID 列,但它与数组中的位置值相同。

这是我的 DatabaseHelper 类中的删除函数

    public void deleteProduct(long ID)
{
    SQLiteDatabase productsdb = this.getWritableDatabase();
    productsdb.execSQL("DELETE FROM  "+ PRODTABLE_NAME +" WHERE ID = "+ ID);

}

任何人都可以阐明如何获取数据库 ID 值吗?

最佳答案

Long 是被单击项目的行 ID,而不是数据库中产品的 ID。

在 DBHelper 类中创建一个返回 ID 的方法,参数为 String ProductName

编辑onItemLongClick()

 @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            TextView prdName = arg1.findViewById(R.id.textView_prdname);

            // now call the method which take productName as parameter and return productId
            int prdID = productDB.getProductID(prdName.getText().toString());

            // Now Pass that ID to deleteProduct
            productDB.deleteProduct(prdID);
            Toast.makeText(medicineList.this, "Item Deleted", Toast.LENGTH_LONG).show();
            finish();
            startActivity(getIntent());

            return true;
        }

此外,如果名称是唯一的而不是DELETE FROM table WHERE ID = id,您可以使用
DELETE FROM table WHERE NAME = name 这里的name可以通过prdName.getText()获取
这样你只需要执行一个查询即可。

关于java - SQLite ID 列和 onItemLongClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314667/

相关文章:

java - 在 JDBC/iBatis 3 中迭代大型结果集的最佳方法是什么?

java - Java 为什么会为你初始化变量呢?

postgresql - 如何从 SpatialLite 合并到 PostGIS?

SQLite浮点问题

java - Android 获取 url,需要登录

java - 同步块(synchronized block)未锁定对象引用

java - "java.lang.UnsatisfiedLinkError: Native method not found:"去掉头文件可以修复错误吗?

java - Android NDK 相机路径 getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)

java - 从原始值键值对 hashmap Java 中获取键值对

php - 在 PHP 中,如何使用 HTML 内容显示数据库中 BLOB 字段中的各种图像?