-2

I want to check if the table has rows and if it contains, then I want to delete it. Below is my code for checking if table has rows in it.

     boolean empty = true;
    Cursor cursor = db.rawQuery("SELECT count(*) FROM TABLE_NAME",null);
    cursor.moveToFirst();
    if (cursor.getInt(0) > 0)
    {
        empty = false;
    }
    else
    {
        empty= true;
    }
    return  empty; 

I even tried checking with below code,

    boolean empty = true;
    Cursor cur = db.rawQuery("SELECT COUNT(*) FROM TABLE_NAME", null);
    if (cur != null && cur.moveToFirst()) {
        empty = (cur.getInt (0) == 0);
    }
    cur.close();

    return empty;    

Both of the above code, throws NullPointerException in line

("SELECT COUNT(*) FROM TABLE_NAME", null);

Any help would be great !! Thanks

Anusha
  • 939
  • 3
  • 13
  • 31

1 Answers1

1

Android comes with a utility class called DatabaseUtils which has a method queryNumEntries that can take your database object and table name as parameter and return the total number of records on that database. Quite a clean way. You don’t need to be writing ‘Select Count(*) from mytable‘ kind of stuffs.

public long count() {
    return DatabaseUtils.queryNumEntries(db,'myTablename');
}

next to delete he rows if your database is not empty try deleteAll to delete all the rows in dB, or use delete_byID() by passing the ID as parameter to the row which you want to delete.

public int deleteAll(){
    return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}

public void delete_byID(int id){
    sqLiteDatabase.delete(MYDATABASE_TABLE, KEY_ID+"="+id, null);
}
CL.
  • 173,858
  • 17
  • 217
  • 259
Akshay Chopde
  • 670
  • 4
  • 10