简体   繁体   中英

Check if certain content exists in SQLite

I have a SQLite Table with 3 Fields: the first is the id (auto increment), the second is called markerID (String) and the third score (Integer).

I want to add a new line if the current markerID of the activity does not already exist in the Table.

The Problem is, as the cursor goes through the entries and there is already an entry that has not the current markerID , it adds a new one for every different markerID stored in the table even if it shoudn't because the current markerID already exists.

How can I check if the markerID doesn't exist at all instead of just asking if it does not equal the current markerID ?

if (cursor.moveToFirst()) {
                do {
                    Log.d("Database", "Inhalt: "+ cursor.getString(0) + cursor.getString(1));

                    if (Integer.parseInt(cursor.getString(0)) < 5 && cursor.getString(1).equals(markerID)) {
                    /*markerID exists: Update Entry*/
                        dbh.updateScore(dbh, Integer.parseInt(cursor.getString(0)), markerID, score);
                        finish();
                    }

                    else if (!cursor.getString(1).equals(markerID) ){
                        /*markerID does not exist in Table: add new, but not for every entry where it does not equal to the current!*/
                        dbh.addScore(dbh, score, markerID);
                        finish();
                    }
                } while (cursor.moveToNext());
           }
            else {
                /*Add first entry*/
                dbh.addScore(dbh, score, markerID);
                finish();
            }

This is how I generate the cursor in my DbHelper class:

 public Cursor getScore(DbHelper dbh) {
    dbase = dbh.getReadableDatabase();
    String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
    Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
    return cursor;
}

The method

public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

has a parameter 'selection', where you can put your markerID. Something like this:

Cursor cursor = dbase.query(SCORE_TABLE, columns, "markerId = 'your string'", null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
    // you have rows with this marker id
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM