Sabre
Sabre

Reputation: 4183

How to check whether the specific value exists in a column?

I'm trying to check if the value exists in a column. For example I want to check that column artId contains some numeric value. I'm using following code:

getStar = db.query(TABLE_NAME, new String[] { "artId" },
                        "artId = " + entryId, null, null,
                        null, null);
        getStar.moveToFirst();
        String star = getStar.toString();
        Log.w("ID COUNT", star);
        if(getStar != null) {
            // do something
        }

Where entryId is some number.

But I always get something like this:

W/ID COUNT(11303): android.database.sqlite.SQLiteCursor@41aa4c80.

Also I tried to use:

getStar = db.rawQuery("SELECT count(*) FROM "
+ TABLE_NAME + " WHERE artId = '" + entryId + "'", null);

But I got the same result.

So I hope for your help.

Upvotes: 1

Views: 3401

Answers (3)

florianmski
florianmski

Reputation: 5643

You are logging the cursor String representation, not the value of the column artId. To get the value of the column artId from your cursor you have to something like this :

int count = -1;
// if the cursor is not empty
if(getStar.moveTofirst())
    count = getStar.getInt(getStar.getColumnIndex("artId");

if(count != -1)
    // do something

Upvotes: 0

Cat
Cat

Reputation: 67502

The Cursor is valid (non-null), yes, because it has no errors. Check if it has any data, instead.

getStar = db.rawQuery("SELECT count(*) FROM " + TABLE_NAME + " WHERE artId = '" + entryId + "'", null);
getStar.moveToFirst();
if (getStar.getInt(0)) { // This will get the integer value of the COUNT(*)
    // It has data
}

I'm a bit unsure of the results of the above; instead, you could query the number of results:

getStar = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE artId = '" + entryId + "'", null);
if (getStar.getCount() > 0) { // This will get the number of rows
    // It has data
}

Upvotes: 5

Marcin S.
Marcin S.

Reputation: 11191

moveTofirst() method try to move the cursor into the first position (0 based) and it returns true if that can be done. Otherwise it returns false. So you could do like that:

if (getStar.moveToFirst) {
// your code
} else {}

if there is an value if statement will be executed otherwise it won't

Upvotes: 1

Related Questions