行未从SQLite中删除

时间:2019-05-05 21:13:45

标签: android android-sqlite

我试图从输入中删除“目标体重”,“目标日期”和“当前体重”的行。它没有出错,但是该行没有被删除。

DeleteLayout

Button deleteB;
    DatabaseHelper myDB;
    EditText goalD;
    EditText goalW;
    EditText currentW;
    Intent j;
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.deletelayout);
        deleteB = findViewById(R.id.buttonDelete);
        myDB = new DatabaseHelper(this);

        deleteB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goalD = findViewById(R.id.goaldinput2);
                goalW = findViewById(R.id.goalwinput3);
                currentW = findViewById(R.id.currentWinput2);
                if(goalD.length() !=0 && goalW.length() !=0 && currentW.length() !=0){
                    Toast.makeText(DeleteLayout.this,"Goal Date: " +goalD.getText().toString()+ "Goal Weight: " + goalW.getText().toString()+
                                    "Current Weight: " +currentW.getText().toString()+ " entered.",
                            Toast.LENGTH_LONG).show();
                    myDB.deleteContent(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());

                    j = new Intent(DeleteLayout.this, historyActivity.class);
                    startActivity(j);



                }
                else{
                    Toast.makeText(DeleteLayout.this,"All data not entered.", Toast.LENGTH_LONG).show();
                }

            }
        });

在DatabaseHelper中删除方法

public void deleteContent(String goalDate, String goalWeight,String currentWeight){
            SQLiteDatabase db = this.getWritableDatabase();
            String query = " DELETE FROM " + TABLE_NAME + "WHERE GDATE = "+
                    goalDate + " AND " + "GWEIGHT = " + goalWeight + " AND " + "CWEIGHT = " + currentWeight  ;
    }

1 个答案:

答案 0 :(得分:0)

主要问题(不是唯一的问题)是在deleteContent()内,尽管您创建了SQL语句,但是您从未说过execSQL()来执行它。
因此,不会尝试删除任何行。
但是,您应该更改为使用delete()方法,如下所示:

public int deleteContent(String goalDate, String goalWeight, String currentWeight){
    SQLiteDatabase db = this.getWritableDatabase();
    String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
    int rows = db.delete(TABLE_NAME, where, new String[] {goalDate, goalWeight, currentWeight});
    db.close();
    return rows;
}

这是推荐的方法,因为它是安全的,并且它还会返回受影响/已删除的行数(您可以检查该行以检查删除是否成功)。
因此您可以像这样使用它:

int rows = myDB.deleteContent(
        goalD.getText().toString(), 
        goalW.getText().toString(), 
        currentW.getText().toString()
);

,在变量rows中,将具有已删除的行数。