开发者

Delete all rows from a table, throws nullpointer

I'm trying to write a function that will delete every row in a given table but I'm getting a null pointer exception. Could somebody point me 开发者_Go百科in the right direction? Here is the code...

   public void deleteall(){
    SQLiteDatabase db = tweets.getWritableDatabase();
    String delete = "TRUNCATE FROM tweets";
    db.rawQuery(delete, null);

      }


Check if tweets is null.

I think it's more simpler to use this call, than using rawQuery. Your rawQuery must be parsed, but using the delete method it uses already a parametrized query.

db.delete('tweets',null,null);


just to delete all rows, you can use following method.

void deleteAll()
{
    SQLiteDatabase db= this.getWritableDatabase();
    db.delete(table_name, null, null);

}


    dataBaseHelper = new DataBaseHelper(getApplicationContext(), DataBaseHelper.DataBaseName, null, 1);
    sqLiteDatabase = dataBaseHelper.getWritableDatabase();
    if (sqLiteDatabase != null) {
        sqLiteDatabase.delete(DataBaseHelper.TableName, null, null);
        Toast.makeText(MainActivity.this, "Refresh", Toast.LENGTH_SHORT).show();
    } else
        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
    break;
}


I was getting a null pointer exception, and then I realised that my method was not calling db.open() first. Added that (and db.close()) and it worked.


SQLite does not have any TRUNCATE statement, so you must do:

public void deleteall(){
    SQLiteDatabase db = tweets.getWritableDatabase();
    String delete = "DELETE FROM tweets";
    db.rawQuery(delete, null);
}


The right answer is this:

db.delete('tweets',"1",null);

From Android official documentation: SQLiteDatabase

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜