如何从数据库表中删除特定项目?

时间:2019-06-02 20:50:32

标签: java android sqlite

我想创建一个待办事项列表应用,我想通过点击复选框删除列表中的项目。

我试图在数据库类中创建一个“ deleteTask”(如代码所示)方法。此外,您可以看到“ populateListView”  方法,它将数据从数据库提供到列表视图中,每次从数据库删除任务后,我都会使用它刷新。

 public void deleteTask(String task) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, COL2 , new String[]{task});
    }

 public void populateListView() {
        try {
            mDataBaseHelper = new DataBaseHelper(MainActivity.this);
            data = mDataBaseHelper.getData();
            mArrayList = new ArrayList<>();
            if (data.getCount() != 0) {
                while (data.moveToNext()) {
                    mArrayList.add(data.getString(1));
                    ListAdapter listAdapter = new ArrayAdapter(MainActivity.this, R.layout.list_items, R.id.checkBox, mArrayList);
                    list = (ListView) findViewById(R.id.myListId);
                    list.setAdapter(listAdapter);
                }
                mDataBaseHelper.close();
            } else {
                toastMessage("the Database is empty");
            }
        }catch(Exception e){
            Log.e(TAG, "populateListView: error"+e.getStackTrace() );
        }
    }

启动应用程序时,我点击了要删除的项目,但是我发现这些项目开始按顺序从上方删除! 每次点击任何复选框时,一一对应。

2 个答案:

答案 0 :(得分:0)

尝试更换

db.delete(TABLE_NAME, COL2 , new String[]{task});

通过

db.delete(TABLE_NAME, COL2 + " = ?" , new String[]{task});

答案 1 :(得分:0)

您想要:-

public void deleteTask(String task) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, COL2 + "=?" , new String[]{task});
}

如果您没有通过使用db.delete(TABLE_NAME, COL2 , new String[]{task});进行try / catch来捕获错误,则会出现以下异常:-

java.lang.IllegalArgumentException: Too many bind arguments.  1 arguments were provided but the statement needs 0 arguments.

但是

假定顺序删除行而不是根据选中的项目删除行的问题很可能是由于处理选中的项目而引起的。但是,由于未提供此代码,因此只能猜测是要知道您在哪里出错了。

有一件事是您不想在每次填充ListView时都创建一个新的listadapter实例。

作为处理ListView的提示,但是在长按COL2值删除项目时删除该项目,也许考虑以下基于您的代码的项目(但根据长按项目进行删除):

public void populateLisView() {
    mDataBaseHelper = new DataBaseHelper(this);  //<<<<<<<<<< NOTE 1
    list = (ListView) this.findViewById(R.id.myListId); //<<<<<<<<<< NOTE 1
    data = mDataBaseHelper.getData(); //<<<<<<<<<< get the data to be listed

    if (listadapter == null) { //<<<<<<<<<< Only need to instantiate one adapter when it has not bee instantiated
        listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data); // for convenience using a stock layout
        list.setAdapter(listadapter);
        //<<<<<<<<<<< add the onItemLongClick listener
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                mDataBaseHelper.deleteTaskByCol2(data.get(position)); //<<<<<<<<<< gets the value of the item according to it's position in the list
                populateLisView(); //<<<<<<<<<< as the item has been deleted then refresh the Listview
                return true; // flag the event as having been handled.
            }
        });
    //<<<<<<<<<<< If the Adapter has been instantiated then refresh the ListView's data
    } else {
        listadapter.clear(); // Clear the data from the adapter
        listadapter.addAll(data); // add the new changed data to the adapter
        listadapter.notifyDataSetChanged(); // tell the adapter that the data has changed
    }
}
  • 注意1

    • 您通常一次将这些变量实例化一次。
  • 检查评论

您可能希望编辑问题以包括如何处理检查事件。

完整的示例

DatabaseHelper.java

  • 请注意,这可能与您有所不同

    公共类DataBaseHelper扩展了SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;
    
    public static final String TABLE_NAME = "mytable";
    public static final String COL1 = "col1";
    public static final String COL2 = "col2";
    
    SQLiteDatabase db;
    
    private static final String CRT_MYTABLE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
            "(" +
            COL1 + " TEXT, " +
            COL2 + " TEXT" +
            ")";
    public DataBaseHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        db = this.getWritableDatabase();
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CRT_MYTABLE_SQL);
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    }
    
    public long addMytableRow(String col1, String col2) {
        ContentValues cv = new ContentValues();
        cv.put(COL1,col1);
        cv.put(COL2,col2);
        return db.insert(TABLE_NAME,null,cv);
    }
    
    public ArrayList<String> getData() {
        ArrayList<String> rv = new ArrayList<>();
        Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
        while (csr.moveToNext()) {
            rv.add(csr.getString(csr.getColumnIndex(COL2)));
        }
        csr.close();
        return rv;
    }
    
    public void deleteTaskByCol2(String task) {
        db.delete(TABLE_NAME,COL2 + "=?",new String[]{task});
    }
    

    }

MainActivity.java

即一个基于您的代码但根据上面的示例活动:-

public class MainActivity extends AppCompatActivity {

    DataBaseHelper mDataBaseHelper;
    ArrayList<String> data;
    ListView list;
    ArrayAdapter<String> listadapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addSomeTestData();
        populateLisView();
    }

    private void example001() {
    }

    public void populateLisView() {
        mDataBaseHelper = new DataBaseHelper(this);
        list = (ListView) this.findViewById(R.id.myListId);
        data = mDataBaseHelper.getData();
        if (listadapter == null) {
            listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data);
            list.setAdapter(listadapter);
            list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    //mDataBaseHelper.deleteTaskWrong(data.get(position)); // ooops
                    mDataBaseHelper.deleteTaskByCol2(data.get(position));
                    populateLisView();
                    return true;
                }
            });
        } else {
            listadapter.clear();
            listadapter.addAll(data);
            listadapter.notifyDataSetChanged();
        }
    }

    private void addSomeTestData() {
        if (mDataBaseHelper == null) {
            mDataBaseHelper = new DataBaseHelper(this);
        }
        if (DatabaseUtils.queryNumEntries(mDataBaseHelper.getWritableDatabase(),DataBaseHelper.TABLE_NAME) > 0) return;
        mDataBaseHelper.addMytableRow("Test1","Test1");
        mDataBaseHelper.addMytableRow("Test2","Test2");
        mDataBaseHelper.addMytableRow("Test3","Test3");
        mDataBaseHelper.addMytableRow("Test4","Test4");
    }
}
  • 注意AddSomeTestData添加了一些用于测试/演示的数据。

结果

首次运行时:-

enter image description here

长按测试2

之后

enter image description here

即长期单击的项目已从列表和数据库中删除,并且列表已刷新。