I have this method which checks whether a table exists in that database or not.However it always returns true.
public boolean checkDomainTableExists(String domain){
if (database==null||!database.isOpen()){
database=dBHelper.getReadableDatabase();
}
if (!database.isReadOnly()){
database.close();
database=dBHelper.getReadableDatabase();
}
try{
cursor=database.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", new String[] {"table", tableName});
}catch (Exception e){
Log.d("exception",e.getLocalizedMessage());
}
if (cursor!=null){
if (cursor.getCount()>0){
cursor.close();
return true;
}
cursor.close();
}
return false;
}
While I am debugging, I see the cursor
count as -1 by the time it reaches to if (cursor.getCount()>0){
and cursor count become 1 when I step over the breakpoint
resulting in method return true
.
Whatever the tablename I give, this method always return true.
Here are the screenshots for debug console:
At this point the cursor count is -1, so I believe it shouldn't get into the loop, but it does and the count goes to 1.
Edit: I also tried the following query:
database.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
Even in this case, getCount is 1 always.
and
try{
cursor=database.query(tableName,null,null,null,null,null,null);
tableExists=true;
}catch (Exception e){
Log.d("exception",e.getLocalizedMessage());
}
Here the bool tableExists is always false.
Where am I doing wrong ?
SELECT COUNT(*)
will always return one entry. Rather than looking at getCount()
, move to the 0th position and call getInt(0)
to retrieve the value generated by SELECT COUNT(*)
. There, you are looking for 0 or 1, presumably.