尝试执行删除查询时遇到错误

时间:2016-11-25 07:12:40

标签: android sqlite insert delete-row

我想在适配器类中单击按钮时执行2查询,首先是从表A中选择数据并插入表B,另一个是从表A中删除行。

适配器

 mdb = new MyDatabaseHelper(v.getContext());
 database = mdb.getReadableDatabase();
 deleteTask = new DeleteTask();
 Cursor cursor = database.rawQuery("SELECT * FROM " + MyDatabaseHelper.TABLE__TASK + " WHERE ID = ? ", new String[]{id+""}, null);
 if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
              String allTask = cursor.getString(cursor.getColumnIndex("Title"));
             String name = cursor.getString(cursor.getColumnIndex("Name"));
             String allTime = cursor.getString(cursor.getColumnIndex("Time"));
             String allDate = cursor.getString(cursor.getColumnIndex("Date"));
             insertDataToCompleteTab(id, name, allTask, allTime, allDate); //insert to Completed table
             deleteTask.deleteData(id); // delete the row of data from Task Table
       }
 }

DeleteTask活动

  public void deleteData(int id)
    {
        database = mdb.getWritableDatabase();
        database.delete(MyDatabaseHelper.TABLE__TASK, MyDatabaseHelper.ID1 + "=" + id,null);
        database.close();
    }

错误

java.lang.NullPointerException
            at com.example.seng.healthyapp.DeleteTask.deleteData(DeleteTask.java:124)
            at com.example.seng.healthyapp.adapter.AllAdapter$1.onClick(AllAdapter.java:139)
            at android.view.View.performClick(View.java:4230)

指向deleteTask方法的错误。但我已经完成了初始化,为什么我仍然会出现这样的错误?

3 个答案:

答案 0 :(得分:0)

它对我有用,试一试......你可以改变这段代码来删除所有..

db= myDb.getWritableDatabase();
db.delete(TABLE_NAME, " ID=? " , new String[] {id},null);
db.close();

答案 1 :(得分:0)

在此处搜索后,我决定删除deleteTask = new DeleteTask();,然后使用deleteData(id)代替deleteTask.deleteData(id);。调用适配器内部的方法但不调用适配器中的其他类对象。

答案 2 :(得分:-1)

这是因为您在删除查询中传递null,请更新您的代码并检查

public void deleteData(int id)
    {
        database = mdb.getWritableDatabase();
        database.delete(MyDatabaseHelper.TABLE__TASK, MyDatabaseHelper.ID1 + "=?" , new String[] {id});
        database.close();
    }