Android - 如何检查数据库中是否存在项目?

时间:2015-06-02 09:41:56

标签: android database cursor

我想在我的数据库中添加一个新项目(spot),但在此之前,我想检查这个项目是否已经存在。

这是我的代码:

for (Spot spot : spotsList)
{
                if (dbHelper.getSpotWithDistantId(spot.getDistantId()) == null)
                {
                    dbHelper.addSpot(spot);
                }
}

这是我的getSpotWithDistantId方法:

public Spot getSpotWithDistantId(int distantId)
    {
        Cursor cursor =
                db.query(TABLE_SPOTS,
                        SPOTS_COLUMNS,
                        " " + KEY_DISTANTID + " = ?",
                        new String[]{String.valueOf(distantId)}, // Selections args
                        null, // Group by
                        null, // Having
                        null, // Order by
                        null); // Limit

        if (cursor != null)
        {
            cursor.moveToFirst();
        }

        Spot spot = buildSpotWithCursor(cursor);

        if (cursor != null)
        {
            cursor.close();
        }

        db.close();

        return spot;
    }

问题是当我想检查某个点是否存在时,会出现以下错误:

  

android.database.CursorIndexOutOfBoundsException:请求索引0,   大小为0

我的代码出了什么问题?

提前致谢。

2 个答案:

答案 0 :(得分:1)

我有类似的问题,我使用这个简单的功能:

public boolean exists_the_ColumnParameter(String query){
    //Declaration of variables
    Cursor a2 = null;

    try{
        OpenDB();
        a2 = database.rawQuery(query,null);

        if(a2 != null) {
            a2.moveToFirst();

            if (a2.getString(0).equals("")) {
                a2.close();
                database.close();
                return false;
            } else {
                a2.close();
                database.close();
                return true;
            }
        }else{
            a2.close();
            database.close();
            return false;
        }

    }
    catch (CursorIndexOutOfBoundsException ex){
        return false;
    }
    catch (NullPointerException ex){
        return false;
    }
    catch (Exception ex){
        Log.e("-- BDD.exists_the_ColumnParameter --","Exception",ex);
        return false;
    }
}

我无法传递单个ID的原因是因为它不是通用函数,最大的区别在于ID只能查看一个SQLite表并且与查询您可以从不同的表中查看多个ID。

告诉我,如果我可以帮助你,那么好的编程!!

答案 1 :(得分:1)

您需要检查光标是否包含任何记录。你可以这样做

if(cursor != null && cursor.getCount() > 0)
{
    ...
}
else
{
    cursor.close();
    return false;
}