【问题标题】:How to delete selected rows in sqlite android using checkbox如何使用复选框删除sqlite android中的选定行
【发布时间】:2015-07-01 19:47:53
【问题描述】:

我的自定义列表视图中的每一行旁边都有一个复选框。用户选择他想要删除的行。我想要完成的是使用复选框仅删除选定的行。以下是我尝试过的:

关于我的活动:

public boolean onOptionsItemSelected(MenuItem item) {
 int id = item.getItemId();

if (id == R.id.action_delete_selected) {
CheckBox cb = (CheckBox)findViewById(R.id.checkBox);

            if (cb.isChecked()) {
                myDb.deleteSingleContact(id);
                Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                showTable();
            }

在我的 DBHelper 中:

public void deleteSingleContact(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_ID+"="+id,null);

           }

但是代码不会删除行并且仍然显示 toast。我缺少什么?任何帮助将不胜感激。 编辑 我的完整活动代码:

public class MyBasket extends ActionBarActivity {
    ListView obj;
    DBHelper myDb;
    int numRows;
    int id_To_Update = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_basket);
        Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        myDb = new DBHelper(this);
        obj = (ListView) findViewById(R.id.listView1);
        Button btn = (Button) findViewById(R.id.checkout);
        if (myDb.checkForTables()) {
            showTable();
            btn.setVisibility(View.VISIBLE);
        } else {
            showAlert();
            btn.setVisibility(View.GONE);
        }

        TextView txt = (TextView) findViewById(R.id.numRows);
        int profile_counts = myDb.numberOfRows();
        myDb.close();
        txt.setText(String.valueOf(profile_counts));
        TextView txt2 = (TextView) findViewById(R.id.Amount_textView);
        int i = myDb.getTotalOfAmount();
        txt2.setText("" + i);

        Button basketButton = (Button) findViewById(R.id.checkout);
        basketButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MyBasket.this, CheckOut.class);
                startActivity(intent);
            }
        });
    }

    public void showAlert() {
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.empty_basket, null);
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setView(layout);
        adb.setCancelable(false);

        adb.setPositiveButton("Add items to basket", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent i = new Intent(MyBasket.this, MainActivity.class);
                startActivity(i);
            }
        });
        adb.show();
    }

    private void showTable() {
        ArrayList<ContactListItems> contactList = myDb.getAllContacts();

        ContactListAdapter contactListAdapter = new ContactListAdapter(
                MyBasket.this, contactList);
        //adding it to the list view.
        obj = (ListView) findViewById(R.id.listView1);
        obj.setAdapter(contactListAdapter);
        obj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                deleteDialog();
            }
        });
        obj.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                myDb.deleteSingleContact(arg2);
                showTable();
                return true;
            }
        });
    }

    private void deleteDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder (MyBasket.this);
        alertDialog.setCancelable(false);
        alertDialog.setMessage("Delete item?");
        alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              myDb.deleteSingleContact(which);
            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();

            }
        });
        alertDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_my_basket, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(MyBasket.this, Settings.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_delete) {
            myDb.deleteContact();
            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MyBasket.this, MyBasket.class);
            startActivity(intent);
            return true;

        }
        if (id == R.id.action_delete_selected) {
            CheckBox cb = (CheckBox)findViewById(R.id.checkBox);

            if (cb.isChecked()) {
                myDb.deleteSingleContact(id);
                Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                showTable();
            }

            return true;

        }
        if (id == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}

完整的 DBHelper:

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_TITLE = "title";
    public static final String CONTACTS_COLUMN_AMOUNT = "amount";
    public static final String CONTACTS_COLUMN_DESC = "description";

    private HashMap hp;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, title text,amount float,description text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact(String title,  float amount, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("title", title);
        contentValues.put("amount", amount);
        contentValues.put("description", description);


        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from contacts where id=" + id + "", null);
        return res;
    }

    public int numberOfRows() {
        String countQuery = "SELECT  * FROM " + CONTACTS_TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int cnt = cursor.getCount();
        cursor.close();
        return cnt;
    }

    public boolean updateContact(Integer id, String title, float amount, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", title);
        contentValues.put("amount", amount);
        contentValues.put("description", description);

        db.update("contacts", contentValues, "id = ? ", new String[]{Integer.toString(id)});
        return true;
    }

    public void deleteContact() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete("contacts", null, null);
        db.close();
    }
    public void deleteSingleContact(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_ID+"="+id,null);

           }


    public boolean checkForTables() {
        boolean hasRows = false;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + CONTACTS_TABLE_NAME, null);
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        if(count > 0)
            hasRows = true;
        db.close();
        return hasRows;
    }
    public ArrayList<ContactListItems> getAllContacts() {
        ArrayList<ContactListItems> contactList = new ArrayList<>();
        hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from contacts", null);
        res.moveToFirst();
        while (!res.isAfterLast()) {
                ContactListItems contactListItems = new ContactListItems();

                contactListItems.setTitle(res.getString(res
                        .getColumnIndex("title")));
                contactListItems.setAmount(res.getFloat(res
                        .getColumnIndex("amount")));
                contactListItems.setDescription(res.getString(res
                        .getColumnIndex("description")));
                contactList.add( contactListItems);
                res.moveToNext();
            }
        res.close();
        return contactList;
    }
    public int getTotalOfAmount(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c=db.rawQuery("SELECT SUM(amount) FROM " +CONTACTS_TABLE_NAME,null);
        c.moveToFirst();
        int i=c.getInt(0);
        c.close();
        return i;
    }
}

【问题讨论】:

    标签: android sqlite checkbox


    【解决方案1】:

    你检查过返回值它应该是整数 1

    int rowsDeleted = db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_ID+"="+id,null);
            if(rowsDeleted>0){
                Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
            }
    

    【讨论】:

    • 这应该是评论,删除!
    • 我没有足够的积分来评论别人的帖子:(
    • @shailesh 当我把它放在我的活动中时,这部分是错误的delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_ID+"="+id,null);
    • 你能粘贴完整的功能吗?我在这里没有得到真正的问题。您在其函数中使用了 myDb,然后使用了 db。
    • 我已经用完整的活动和 DBHelper 类编辑了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多