Example usage for android.database Cursor isNull

List of usage examples for android.database Cursor isNull

Introduction

In this page you can find the example usage for android.database Cursor isNull.

Prototype

boolean isNull(int columnIndex);

Source Link

Document

Returns true if the value in the indicated column is null.

Usage

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testSaveAsIncompleteMostRecentCheckpointDataInTableWithId_ExpectPass()
        throws ActionNotAuthorizedException {
    String tableId = testTable;//  w  w  w . jav a2  s  . c  o  m
    String testCol = "testColumn";
    String testColType = ElementDataType.string.name();
    String testVal = "test";
    String testVal2 = "test2";
    String rowId = LocalizationUtils.genUUID();
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column(testCol, testCol, testColType, "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST);

    ContentValues cvValues = new ContentValues();
    cvValues.put(testCol, testVal);
    ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, rowId, activeUser,
            RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Select everything out of the table
    String sel = "SELECT * FROM " + tableId + " WHERE " + testCol + " = ?";
    String[] selArgs = { "" + testVal };
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    String val = null;
    while (cursor.moveToNext()) {
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val = cursor.getString(ind);
    }

    assertEquals(val, testVal);

    ContentValues updatedCvValues = new ContentValues();
    updatedCvValues.put(testCol, testVal2);
    ODKDatabaseImplUtils.get().insertCheckpointRowWithId(db, tableId, orderedColumns, updatedCvValues, rowId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale);

    // Select everything out of the table
    sel = "SELECT * FROM " + tableId;
    selArgs = new String[0];
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    assertEquals(cursor.getCount(), 2);

    // Select everything out of the table
    sel = "SELECT * FROM " + tableId + " WHERE " + testCol + " = ?";
    selArgs = new String[1];
    selArgs[0] = "" + testVal2;
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    String val2 = null;
    String saveptType = null;
    while (cursor.moveToNext()) {
        // Get the actual value
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val2 = cursor.getString(ind);

        // Get the savepoint_timestamp
        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TIMESTAMP);
        type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        saveptType = cursor.getString(ind);

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val2, testVal2);

    // Also make sure that the savepoint_type
    // is empty
    assertNotSame(saveptType, SavepointTypeManipulator.incomplete());
    assertNotSame(saveptType, SavepointTypeManipulator.complete());

    ODKDatabaseImplUtils.get().saveAsIncompleteMostRecentCheckpointRowWithId(db, tableId, rowId);

    // Select everything out of the table
    sel = "SELECT * FROM " + tableId;
    selArgs = new String[0];
    cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext);

    assertEquals(cursor.getCount(), 1);

    val2 = null;
    saveptType = null;
    while (cursor.moveToNext()) {
        // Get the actual value
        int ind = cursor.getColumnIndex(testCol);
        int type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        val2 = cursor.getString(ind);

        // Get the savepoint_timestamp
        ind = cursor.getColumnIndex(DataTableColumns.SAVEPOINT_TYPE);
        type = cursor.getType(ind);
        assertEquals(type, Cursor.FIELD_TYPE_STRING);
        saveptType = cursor.getString(ind);

        // Get the conflict_type and make sure that it is null
        ind = cursor.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
        assertTrue(cursor.isNull(ind));
    }

    assertEquals(val2, testVal2);
    assertEquals(saveptType, SavepointTypeManipulator.incomplete());

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

/**
 * Inserts a checkpoint row for the given rowId in the tableId. Checkpoint
 * rows are created by ODK Survey to hold intermediate values during the
 * filling-in of the form. They act as restore points in the Survey, should
 * the application die./*from  w  w w . j  a va  2  s .  co  m*/
 *
 * @param db
 * @param tableId
 * @param orderedColumns
 * @param cvValues
 * @param rowId
 * @param activeUser
 * @param rolesList
 * @param locale
 */
public void insertCheckpointRowWithId(OdkConnectionInterface db, String tableId, OrderedColumns orderedColumns,
        ContentValues cvValues, String rowId, String activeUser, String rolesList, String locale)
        throws ActionNotAuthorizedException {

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table for checkpoint" + tableId);
    }

    // these are all managed in the database layer...
    // the user should NOT set them...

    if (cvValues.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
        throw new IllegalArgumentException(
                t + ": No user supplied savepoint timestamp can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.SAVEPOINT_TYPE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied savepoint type can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.ROW_ETAG)) {
        throw new IllegalArgumentException(t + ": No user supplied row ETag can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.SYNC_STATE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied sync state can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.CONFLICT_TYPE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied conflict type can be included for a checkpoint");
    }

    // If a rowId is specified, a cursor will be needed to
    // get the current row to create a checkpoint with the relevant data
    Cursor c = null;
    try {
        // Allow the user to pass in no rowId if this is the first
        // checkpoint row that the user is adding
        if (rowId == null) {

            // TODO: is this even valid any more? I think we disallow this in the AIDL flow.

            String rowIdToUse = LocalizationUtils.genUUID();
            HashMap<String, Object> currValues = new HashMap<String, Object>();
            for (String key : cvValues.keySet()) {
                currValues.put(key, cvValues.get(key));
            }
            currValues.put(DataTableColumns._ID, rowIdToUse);
            currValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
            insertCheckpointIntoExistingTable(db, tableId, orderedColumns, currValues, activeUser, rolesList,
                    locale, true, null, null, null, null, null);
            return;
        }

        StringBuilder b = new StringBuilder();
        b.append(K_DATATABLE_ID_EQUALS_PARAM).append(S_AND).append(DataTableColumns.SAVEPOINT_TIMESTAMP)
                .append(" IN (SELECT MAX(").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") FROM ")
                .append(tableId).append(K_WHERE).append(K_DATATABLE_ID_EQUALS_PARAM).append(")");
        c = db.query(tableId, null, b.toString(), new Object[] { rowId, rowId }, null, null, null, null);
        c.moveToFirst();

        if (c.getCount() > 1) {
            throw new IllegalStateException(t + ": More than one checkpoint at a timestamp");
        }

        // Inserting a checkpoint for the first time
        if (c.getCount() <= 0) {
            HashMap<String, Object> currValues = new HashMap<String, Object>();
            for (String key : cvValues.keySet()) {
                currValues.put(key, cvValues.get(key));
            }
            currValues.put(DataTableColumns._ID, rowId);
            currValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
            insertCheckpointIntoExistingTable(db, tableId, orderedColumns, currValues, activeUser, rolesList,
                    locale, true, null, null, null, null, null);
            return;
        } else {
            // Make sure that the conflict_type of any existing row
            // is null, otherwise throw an exception
            int conflictIndex = c.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
            if (!c.isNull(conflictIndex)) {
                throw new IllegalStateException(
                        t + ":  A checkpoint cannot be added for a row that is in conflict");
            }

            // these are all managed in the database layer...
            // the user should NOT set them...

            if (cvValues.containsKey(DataTableColumns.DEFAULT_ACCESS)) {
                throw new IllegalArgumentException(
                        t + ": No user supplied default access can be included for a checkpoint");
            }

            if (cvValues.containsKey(DataTableColumns.ROW_OWNER)) {
                throw new IllegalArgumentException(
                        t + ": No user supplied row owner can be included for a checkpoint");
            }

            if (cvValues.containsKey(DataTableColumns.GROUP_READ_ONLY)) {
                throw new IllegalArgumentException(
                        t + ": No user supplied group read only can be included for a checkpoint");
            }

            if (cvValues.containsKey(DataTableColumns.GROUP_MODIFY)) {
                throw new IllegalArgumentException(
                        t + ": No user supplied group modify can be included for a checkpoint");
            }

            if (cvValues.containsKey(DataTableColumns.GROUP_PRIVILEGED)) {
                throw new IllegalArgumentException(
                        t + ": No user supplied group privileged can be included for a checkpoint");
            }

            HashMap<String, Object> currValues = new HashMap<String, Object>();
            for (String key : cvValues.keySet()) {
                currValues.put(key, cvValues.get(key));
            }

            // This is unnecessary
            // We should only have one row at this point
            //c.moveToFirst();

            String priorDefaultAccess = null;
            String priorOwner = null;
            String priorGroupReadOnly = null;
            String priorGroupModify = null;
            String priorGroupPrivileged = null;

            // Get the number of columns to iterate over and add
            // those values to the content values
            for (int i = 0; i < c.getColumnCount(); i++) {
                String name = c.getColumnName(i);

                if (name.equals(DataTableColumns.DEFAULT_ACCESS)) {
                    priorDefaultAccess = c.getString(i);
                }

                if (name.equals(DataTableColumns.ROW_OWNER)) {
                    priorOwner = c.getString(i);
                }

                if (name.equals(DataTableColumns.GROUP_READ_ONLY)) {
                    priorGroupReadOnly = c.getString(i);
                }

                if (name.equals(DataTableColumns.GROUP_MODIFY)) {
                    priorGroupModify = c.getString(i);
                }

                if (name.equals(DataTableColumns.GROUP_PRIVILEGED)) {
                    priorGroupPrivileged = c.getString(i);
                }

                if (currValues.containsKey(name)) {
                    continue;
                }

                // omitting savepoint timestamp will generate a new timestamp.
                if (name.equals(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
                    continue;
                }

                // set savepoint type to null to mark this as a checkpoint
                if (name.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                    currValues.put(name, null);
                    continue;
                }

                // sync state (a non-null field) should either remain 'new_row'
                // or be set to 'changed' for all other existing values.
                if (name.equals(DataTableColumns.SYNC_STATE)) {
                    String priorState = c.getString(i);
                    if (priorState.equals(SyncState.new_row.name())) {
                        currValues.put(name, SyncState.new_row.name());
                    } else {
                        currValues.put(name, SyncState.changed.name());
                    }
                    continue;
                }

                if (c.isNull(i)) {
                    currValues.put(name, null);
                    continue;
                }

                // otherwise, just copy the values over...
                Class<?> theClass = CursorUtils.getIndexDataType(c, i);
                Object object = CursorUtils.getIndexAsType(c, theClass, i);
                insertValueIntoContentValues(currValues, theClass, name, object);
            }

            insertCheckpointIntoExistingTable(db, tableId, orderedColumns, currValues, activeUser, rolesList,
                    locale, false, priorDefaultAccess, priorOwner, priorGroupReadOnly, priorGroupModify,
                    priorGroupPrivileged);
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
}