Check if Cursor data is exists or not with SQLite database in Android


When creating a data, sometimes we need to check whether there is a previous data that can be updated or not. To check if data is exists or not, we can use “cursor.moveToFirst()” instead of “cursor.getCount() > 0”. Simple example :

1
2
3
4
5
6
7
8
9
// Check if days is exists
mCursor = database.query(dbHelper.TABLE_TRACKER,
        allColumns, dbHelper.COLUMN_DAY + "=?",
        new String[] {Integer.toString(day)}, null, null, null, null);
       
// If data exists, then update the records
if(mCursor.moveToFirst()) {
    // Do your update logic here
}

But, then we can do enhancement like if data exists, then update the data. Meanwhile, if there no records, then create a new records. Here is the implementation :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Cursor mCursor;

// Check if days is exists
mCursor = database.query(dbHelper.TABLE_TRACKER,
        allColumns, dbHelper.COLUMN_DAY + "=?",
        new String[] {Integer.toString(day)}, null, null, null, null);
       
// If data exists, then update the records
if(mCursor.moveToFirst()) {
    database.update(dbHelper.TABLE_TRACKER, values,
            dbHelper.COLUMN_ID + "=?",
            new String[] {String.valueOf(mCursor.getColumnIndex("id"))}
    );

} else {
    // Set the new records ID
    long insertId = database.insert(dbHelper.TABLE_TRACKER, null, values);
   
    // Inserting a new records
    mCursor = database.query(dbHelper.TABLE_TRACKER,
            allColumns, dbHelper.COLUMN_ID + " = " + insertId,
            null, null, null, null);
   
    mCursor.moveToFirst(); // To get the records
}


mCursor.close()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.