android检查表是否为空

时间:2014-07-28 12:25:39

标签: android database sqlite

我工作sqllite.i成功创建了数据库,我可以在我的数据库中添加/删除/更新 现在我想写函数来检查表是否为空。如果表是空显示空吐司消息否则另一个吐司消息 我写了一些代码但是awlays Toast消息是空的 这是我的代码

public boolean checkForTables(){
    boolean hasTables = false;
    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " +TABLE_CONTACTS, null);

    if(cursor.getCount() == 0){
        hasTables=false;
    if(cursor.getCount() > 0){
        hasTables=true;
    }

    cursor.close();
    }
    return hasTables;


}

我在另一个活动中检查此功能,但正如我所说的那样,消息是空的

if(helper.checkForTables())
        Toast.makeText(getActivity(), "not empty", Toast.LENGTH_SHORT).show();

    else
        Toast.makeText(getActivity(), "empty", Toast.LENGTH_SHORT).show();

如果有人知道解决方案,我做错了什么,请帮助我

4 个答案:

答案 0 :(得分:4)

您以错误的方式嵌套if语句。这样,假设其余部分是正确的,应该有效:

public boolean checkForTables(){
    boolean hasTables = false;
    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " +TABLE_CONTACTS, null);

    if(cursor != null && cursor.getCount() > 0){
        hasTables=true;
        cursor.close();
    } 

    return hasTables;
}

顺便说一句,执行SELECT COUNT(*)应该更有效:

public boolean checkForTables(){

  db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " +TABLE_CONTACTS, null);

  if(cursor != null){

    cursor.moveToFirst();

    int count = cursor.getInt(0);

    if(count > 0){
      return true;
    }

    cursor.close();
  } 

  return false;
}

答案 1 :(得分:1)

if条件错误,试试这个:

public boolean checkForTables(){
    db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " +TABLE_CONTACTS, null);
    if(cursor != null && cursor.getCount() > 0){
        cursor.close();
        return true;
    } 
    return false;
}

答案 2 :(得分:0)

你错了你的括号:

if(cursor.getCount() == 0){
    hasTables=false;
if(cursor.getCount() > 0){
    hasTables=true;
}

cursor.close();
}

到此:

if(cursor.getCount() == 0){
    hasTables=false;
}
else if(cursor.getCount() > 0){
    hasTables=true;
}

cursor.close();

答案 3 :(得分:0)

你可以尝试:

Cursor cursor = db.rawQuery(select count(*) from +TABLE_CONTACTS, null);
cursor.moveToFirst();
int count= cursor.getInt(0);

if(count == 0){
    hasTables=false;
}
else if(count > 0){
    hasTables=true;
}
相关问题