Android SQLite检查表是否包含行

dee*_*mel 3 database sqlite android

所以我正在开发一款针对Android的游戏,而且我目前仍然停留在主菜单中的"加载存档"按钮.此按钮调用从数据库读取数据的方法,并将其写入资源类,从该资源类中将访问此数据.

问题是:如果表中没有行,我想禁用加载按钮,这意味着不存在savegame.

为此,我使用以下方法:

public boolean checkForTables(){
    boolean hasTables;
    String[] column = new String[1];
    column[0] = "Position";
    Cursor cursor;
    cursor = db.query("itemtable", column, null, null, null, null, null);
    if(cursor.isNull(0) == true){
        hasTables=false;
    }else{
        hasTables=true;
    }
    return hasTables;
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它会在其中一个数据库表上启动查询,并检查0列(该列中唯一应该位于此列中的列)是否为空.ATM我无法检查此调用的logcat结果,因为我似乎遇到了一些问题,但似乎查询抛出异常,因为该表为空.

有没有想过检查表的行?

_ __ _ __ _ __ _ __ _ __ _ __ _ _EDIT_ _ __ _ __ _ __ _ __ _

注意:我检查了数据库,确实是空的

好吧我在表上使用了rawQuery但是使用count-statement的方法产生了一个错误,所以我正在使用

public boolean checkForTables(){
        boolean hasTables;

        Cursor cursor = db.rawQuery("SELECT * FROM playertable", null);

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

        cursor.close();
        return hasTables;
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用此方法来决定是否禁用loadGame按钮,如下所示:

loadGame = (ImageButton) findViewById(R.id.loadButton);
    loadGame.setEnabled(databaseAccess.checkForTables());
    loadGame.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            databaseAccess.loadPlayer();
            databaseAccess.loadItems();
            databaseAccess.dropTables();

        }
    });
Run Code Online (Sandbox Code Playgroud)

因此,如果checkForTables得到一个!= 0的行数,它将返回true,因此启用Button,或者如果rowcount = 0则禁用它

有趣的是,尽管表是空的,但checkForTables()返回true,因为getCount()似乎返回了一个!= 0的值 - 我只是没有得到它.

mah*_*mah 16

执行诸如的查询select count(*) from itemtable.此查询将生成一个整数结果,其中包含该表中的行数.

例如:

Cursor cursor = db.rawQuery("SELECT count(*) FROM itemtable");
if (cursor.getInt(0) > 0) ... // there are rows in the table
Run Code Online (Sandbox Code Playgroud)

-------------------------------------------------- -----------------------------------

请注意,@ PareshDudhat尝试了以下编辑,但被评论者拒绝了.因为这个答案被张贴我还没有与Android跟上,但研究一个非常简短的一点建议编辑(至少要怎么改rawQuery()叫,我也没检查moveToFirst(),但@ k2col的评论表明,它现在需要的,以及)有价值.

Cursor cursor = db.rawQuery("SELECT count(*) FROM itemtable",null);
cursor.moveToFirst();
if (cursor.getInt(0) > 0) ... // there are rows in the table
Run Code Online (Sandbox Code Playgroud)