How to Delete All Items From SQLite in Android
db.delete(TABLE_NAME, null, null); is the correct syntax to delete all rows in a table. But I think you would have given table name directly without enclosing it in double-quotes. Try like this
db.delete("TABLE_NAME", null, null);
It might help :)
Your delete() call is correct. Did you get writable database? Here is example of method using delete:
/**
* Remove all users and groups from database.
*/
public void removeAll()
{
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = helper.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
db.delete(DatabaseHelper.TAB_USERS, null, null);
db.delete(DatabaseHelper.TAB_USERS_GROUP, null, null);
}
Actually another way I did it was to DROP
the tables and then just call the onCreate
method for the SQLiteDatabase
. I don't know which is most a efficient Delete
or Drop
because I haven't really dug deep into how efficient each method is but it works great for me because in my initial database I have some default values set and so when I call the onCreate
method for the database I have some PUT
methods there also. This saves code replication. ( instead of doing the delete and then the puts I get a multi purpose out of my onCreate
function).
I call it reset
. So you'd just have to do db.reset()
and then the default values are added in the onCreate
after you make your tables.
public void reset () throws SQLException {
db = DBHelper.getWritableDatabase ();
db.execSQL ("drop table "+TABLE_NAME);
db.close ();
this.DBHelper.onCreate (this.db);
}
Use This Code for clear all database content
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
String tableName="";
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
tableName = c.getString( c.getColumnIndex("name"));
if(!tableName.equals('android_metadata')){
db.execSQL("DROP TABLE '"+tableName+"'");
}
c.moveToNext();
}
}
c.close();