Example usage for android.database.sqlite SQLiteDatabase execSQL

List of usage examples for android.database.sqlite SQLiteDatabase execSQL

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase execSQL.

Prototype

public void execSQL(String sql) throws SQLException 

Source Link

Document

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

Usage

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    db.beginTransaction();/*w w  w.  ja  va2  s. c  o m*/

    createTable(db, MyInfo.TABLE, null, MyInfo._ID, "INTEGER PRIMARY KEY", MyInfo.PUBLIC_KEY, "TEXT",
            MyInfo.PRIVATE_KEY, "TEXT", MyInfo.NAME, "TEXT", MyInfo.EMAIL, "TEXT", MyInfo.PICTURE, "BLOB",
            MyInfo.ABOUT, "TEXT DEFAULT ''");

    createTable(db, DbObject.TABLE, null, DbObject._ID, "INTEGER PRIMARY KEY", DbObject.TYPE, "TEXT",
            DbObject.SEQUENCE_ID, "INTEGER", DbObject.FEED_NAME, "TEXT", DbObject.APP_ID, "TEXT",
            DbObject.CONTACT_ID, "INTEGER", DbObject.DESTINATION, "TEXT", DbObject.JSON, "TEXT",
            DbObject.TIMESTAMP, "INTEGER", DbObject.LAST_MODIFIED_TIMESTAMP, "INTEGER", DbObject.SENT,
            "INTEGER DEFAULT 0", DbObject.DELETED, "INTEGER DEFAULT 0", DbObject.HASH, "INTEGER",
            DbObject.ENCODED, "BLOB", DbObject.CHILD_FEED_NAME, "TEXT", DbObject.RAW, "BLOB", DbObject.KEY_INT,
            "INTEGER");
    db.execSQL("CREATE INDEX objects_by_sequence_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
            + DbObject.FEED_NAME + ", " + DbObject.SEQUENCE_ID + ")");
    createIndex(db, "INDEX", "objects_by_feed_name", DbObject.TABLE, DbObject.FEED_NAME);
    db.execSQL("CREATE INDEX objects_by_creator_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
            + DbObject.SENT + ")");
    createIndex(db, "INDEX", "child_feeds", DbObject.TABLE, DbObject.CHILD_FEED_NAME);
    createIndex(db, "INDEX", "objects_by_hash", DbObject.TABLE, DbObject.HASH);
    createIndex(db, "INDEX", "objects_by_int_key", DbObject.TABLE, DbObject.KEY_INT);
    createIndex(db, "INDEX", "objects_last_modified", DbObject.TABLE, DbObject.LAST_MODIFIED_TIMESTAMP);

    createTable(db, Contact.TABLE, null, Contact._ID, "INTEGER PRIMARY KEY", Contact.NAME, "TEXT",
            Contact.PUBLIC_KEY, "TEXT", Contact.PUBLIC_KEY_HASH_64, "INTEGER", Contact.SHARED_SECRET, "BLOB",
            Contact.PERSON_ID, "TEXT", Contact.EMAIL, "TEXT", Contact.PRESENCE,
            "INTEGER DEFAULT " + Presence.AVAILABLE, Contact.LAST_PRESENCE_TIME, "INTEGER DEFAULT 0",
            Contact.LAST_OBJECT_ID, "INTEGER", Contact.LAST_UPDATED, "INTEGER", Contact.NUM_UNREAD,
            "INTEGER DEFAULT 0", Contact.NEARBY, "INTEGER DEFAULT 0", Contact.STATUS, "TEXT", Contact.PICTURE,
            "BLOB", Contact.HIDDEN, "INTEGER DEFAULT 0");
    createIndex(db, "UNIQUE INDEX", "contacts_by_person_id", Contact.TABLE, Contact.PERSON_ID);
    createIndex(db, "INDEX", "contacts_by_pkp", Contact.TABLE, Contact.PUBLIC_KEY_HASH_64);

    createTable(db, Subscriber.TABLE, new String[] { Subscriber.CONTACT_ID, Subscriber.FEED_NAME },
            Subscriber._ID, "INTEGER PRIMARY KEY", Subscriber.CONTACT_ID,
            "INTEGER REFERENCES " + Contact.TABLE + "(" + Contact._ID + ") ON DELETE CASCADE",
            Subscriber.FEED_NAME, "TEXT");
    createIndex(db, "INDEX", "subscribers_by_contact_id", Subscriber.TABLE, Subscriber.CONTACT_ID);

    createGroupBaseTable(db);
    createGroupMemberBaseTable(db);
    createRelationBaseTable(db);
    addRelationIndexes(db);
    createUserAttributesTable(db);
    generateAndStorePersonalInfo(db);

    db.setVersion(VERSION);
    db.setTransactionSuccessful();
    db.endTransaction();
    this.onOpen(db);
    //}
}

From source file:com.melchor629.musicote.MainActivity.java

/** Carga desde la base de datos */
private void cursordb(SQLiteDatabase db) {
    // Define a projection that specifies which columns from the database
    // you will actually use after this query.
    String[] projection = { DB_entry.COLUMN_CANCIONES_ID, DB_entry.COLUMN_CANCIONES_TITULO,
            DB_entry.COLUMN_CANCIONES_ARTISTA, DB_entry.COLUMN_CANCIONES_ALBUM,
            DB_entry.COLUMN_CANCIONES_DURACION, DB_entry.COLUMN_CANCIONES_ARCHIVO,
            DB_entry.COLUMN_CANCIONES_DOWNLOADED };

    // How you want the results sorted in the resulting Cursor
    String sortOrder = DB_entry.COLUMN_CANCIONES_ID + " ASC";

    Cursor c = db.query(DB_entry.TABLE_CANCIONES, // The table to query
            projection, // The columns to return
            null, // The columns for the WHERE clause
            null, // The values for the WHERE clause
            null, // don't group the rows
            null, // don't filter by row groups
            sortOrder // The sort order
    );// w  w w .  j  a v  a2  s .c  o m
    if (songList != null)
        songList.clear();
    else
        songList = new ArrayList<>();

    c.moveToFirst();
    try {
        do {
            // creating new HashMap
            LinkedTreeMap<String, String> map = new LinkedTreeMap<>();

            long id = c.getLong(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ID));
            String titulo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_TITULO));
            String artista = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARTISTA));
            String album = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ALBUM));
            String archivo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARCHIVO));
            String duracion = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DURACION));
            String downloaded = "false";//c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DOWNLOADED));

            // adding each child node to HashMap key => value
            map.put("id", "" + id);
            map.put("titulo", titulo);
            map.put("artista", artista);
            map.put("album", album);
            map.put("archivo", archivo);
            map.put("duracion", duracion);
            map.put("downloaded", downloaded.equalsIgnoreCase("true") ? "{fa-mobile}" : "{fa-cloud}"); //TODO

            songList.add(map);
        } while (c.moveToNext());
    } catch (CursorIndexOutOfBoundsException e) {
        db.execSQL(DB_entry.DELETE_CANCIONES);
        Log.e("DB", "Mala integridad de la BD");
    }
    c.close();
    sis();
}

From source file:org.digitalcampus.oppia.application.DbHelper.java

public void createClientTable(SQLiteDatabase db) {
    String sql = "CREATE TABLE [" + CLIENT_TABLE + "] (" + "[" + CLIENT_C_ID + "]"
            + " integer primary key autoincrement, " + "[" + CLIENT_C_NAME + "]" + " TEXT , " + "["
            + CLIENT_C_MOBILENUMBER + "] integer , " + "[" + CLIENT_C_GENDER + "] TEXT , " + "["
            + CLIENT_C_MARITALSTATUS + "] TEXT , " + "[" + CLIENT_C_AGE + "] integer ," + "[" + CLIENT_C_PARITY
            + "] TEXT ," + "[" + CLIENT_C_LIFESTAGE + "] TEXT ," + "[" + CLIENT_C_MODIFIED_DATE + "] integer , "
            + "[" + CLIENT_C_SERVER_ID + "] integer null , " + "[" + CLIENT_C_HEALTHWORKER + "] TEXT ," + "["
            + CLIENT_C_AGEYOUNGESTCHILD + "] integer default 0 ," + "[" + CLIENT_C_HUSBANDNAME
            + "] TEXT null , " + "[" + CLIENT_C_METHODNAME + "] TEXT null  ," + "[" + CLIENT_CLOSE_CASE
            + "] integer default 0 ," + "[" + CLIENT_DELETE_RECORD + "] integer default 0 ," + "["
            + CLIENT_ADAPTED_METHOD_NAME + "] TEXT null ," + "[" + CLIENT_ADAPTED_METHOD_TIME + "] integer ,"
            + "[" + CLIENT_LAST_CREATED + "] integer default 0 " + ");";
    db.execSQL(sql);
}

From source file:org.mitre.svmp.common.DatabaseHandler.java

private void createTable(int tableID, SQLiteDatabase db) {
    StringBuilder query = new StringBuilder();
    StringBuilder primaryKeys = new StringBuilder();
    StringBuilder foreignKeys = new StringBuilder();

    query.append(String.format("CREATE TABLE %s (", Tables[tableID]));

    for (int i = 0; i < TableColumns[tableID].length; i++) {
        if (i > 0)
            query.append(", ");

        // append column name, type, and constraints
        for (int j = 0; j < TableColumns[tableID][i].length; j++) {
            // if this is a primary key option, add it to the string and save it for the end
            if (j == 2 && TableColumns[tableID][i][j].equals("PRIMARY KEY")) {
                if (primaryKeys.length() > 0)
                    primaryKeys.append(", ");
                primaryKeys.append(TableColumns[tableID][i][0]);
            }//from  w  w  w .  j a v a 2  s . co  m
            // if this is another option (UNIQUE, NOT NULL, etc) add it now
            else {
                if (j > 0)
                    query.append(" ");
                query.append(TableColumns[tableID][i][j]);
            }
        }

        // loop through tables to construct foreign key constraints (looks at 1st column/primary key of each table)
        String foreignTable = "";
        for (int k = 0; k < Tables.length; k++) {

            if (k < tableID // skip the same table, skip tables that haven't been added yet
                    && TableColumns[k][0][0].equals(TableColumns[tableID][i][0])
                    && TableColumns[k][0].length > 2 && TableColumns[k][0][2].equals("PRIMARY KEY")) {
                foreignTable = Tables[k];
                break;
            }
        }
        if (foreignTable.length() > 0) {
            String constraint = String.format(
                    ", FOREIGN KEY (%s) REFERENCES %s (%s) ON DELETE CASCADE ON UPDATE CASCADE",
                    TableColumns[tableID][i][0], foreignTable, TableColumns[tableID][i][0]);
            foreignKeys.append(constraint);
        }
    }

    // append primary key constraint(s)
    if (primaryKeys.length() > 0) {
        query.append(String.format(", PRIMARY KEY (%s)", primaryKeys.toString()));
    }

    query.append(foreignKeys.toString());
    query.append(");");

    Log.d(TAG, String.format("Creating table: %s", query.toString()));

    // try to create the table with the constructed query
    try {
        db.execSQL(query.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.rener.sea.DBHelper.java

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(DBSchema.ENABLE_FOREIGN_KEY);
    db.execSQL(DBSchema.CREATE_ADDRESS_TABLE);
    db.execSQL(DBSchema.CREATE_APPOINTMENTS_TABLE);
    db.execSQL(DBSchema.CREATE_CATEGORY_TABLE);
    db.execSQL(DBSchema.CREATE_DEVICES_TABLE);
    db.execSQL(DBSchema.CREATE_FLOWCHART_TABLE);
    db.execSQL(DBSchema.CREATE_ITEM_TABLE);
    db.execSQL(DBSchema.CREATE_LOCATION_TABLE);
    db.execSQL(DBSchema.CREATE_LOCATION_CATEGORY_TABLE);
    db.execSQL(DBSchema.CREATE_OPTION_TABLE);
    db.execSQL(DBSchema.CREATE_PERSON_TABLE);
    db.execSQL(DBSchema.CREATE_REPORT_TABLE);
    db.execSQL(DBSchema.CREATE_PATH_TABLE);
    db.execSQL(DBSchema.CREATE_SPECIALIZATION_TABLE);
    db.execSQL(DBSchema.CREATE_USERS_TABLE);
    db.execSQL(DBSchema.CREATE_USERS_SPECIALIZATION_TABLE);
    Log.i(this.toString(), "created");
    dummyDB = true;/*w w w.j av a  2 s .  c o m*/

}

From source file:com.rener.sea.DBHelper.java

public void deleteDB() {
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM " + DBSchema.TABLE_ADDRESS + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_APPOINTMENTS + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_CATEGORY + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_DEVICES + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_FLOWCHART + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_ITEM + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_LOCATION + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_LOCATION_CATEGORY + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_OPTION + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_PATH + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_PERSON + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_REPORT + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_SPECIALIZATION + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_USERS + " WHERE 1 = 1 ");
    db.execSQL("DELETE FROM " + DBSchema.TABLE_USERS_SPECIALIZATION + " WHERE 1 = 1 ");
}

From source file:com.rener.sea.DBHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_ADDRESS);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_APPOINTMENTS);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_CATEGORY);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_DEVICES);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_FLOWCHART);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_ITEM);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_LOCATION);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_LOCATION_CATEGORY);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_OPTION);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_PATH);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_PERSON);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_REPORT);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_SPECIALIZATION);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_USERS);
    db.execSQL("DROP TABLE IF EXISTS " + DBSchema.TABLE_USERS_SPECIALIZATION);
    DATABASE_VERSION = newVersion;/*from   w ww  . j ava 2  s  .  c  o m*/
    onCreate(db);
}

From source file:com.rener.sea.DBHelper.java

private void setSequence(long seq) {
    //        deleteDB();
    getDummy();/*w  ww.j av  a 2  s. c  o  m*/
    SQLiteDatabase db = getWritableDatabase();
    Log.i(this.toString(), "SQLITE_SEQUENCE = " + seq);

    Log.i(this.toString(), "SQLITE_SEQUENCE = " + seq);
    //        db.execSQL("DELETE FROM sqlite_sequence WHERE 1 = 1");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_ADDRESS
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'"
            + DBSchema.TABLE_APPOINTMENTS + "');");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_CATEGORY
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'"
            + DBSchema.TABLE_FLOWCHART + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_ITEM
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_LOCATION
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_OPTION
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_PERSON
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_REPORT
            + "');");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_PATH
            + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'"
            + DBSchema.TABLE_SPECIALIZATION + "')");
    db.execSQL("INSERT OR REPLACE INTO sqlite_sequence(seq,name) VALUES(" + seq + ",'" + DBSchema.TABLE_USERS
            + "')");

    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_ADDRESS+"'");
    //        db.execSQL("UPDATE OR REPLACE SQLITE_SEQUENCE SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_APPOINTMENTS+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_CATEGORY+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_FLOWCHART+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_ITEM+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_LOCATION+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_OPTION+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_PERSON+"'");
    //        db.execSQL("UPDATE OR REPLACE SQLITE_SEQUENCE SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_REPORT+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_PATH+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_SPECIALIZATION+"'");
    ////        db.execSQL("UPDATE OR REPLACE sqlite_sequence SET seq = "+seq+" WHERE name = '"+DBSchema.TABLE_USERS+"'");

    db.close();
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void createDBTableWithColumns(SQLiteDatabase db, String appName, String tableId,
        List<ColumnDefinition> orderedDefs) {
    if (tableId == null || tableId.length() <= 0) {
        throw new IllegalArgumentException(t + ": application name and table name must be specified");
    }//ww w  .j  av  a 2s.c  om

    String createTableCmd = getUserDefinedTableCreationStatement(tableId);

    StringBuilder createTableCmdWithCols = new StringBuilder();
    createTableCmdWithCols.append(createTableCmd);

    for (ColumnDefinition column : orderedDefs) {
        if (!column.isUnitOfRetention()) {
            continue;
        }
        ElementType elementType = column.getType();

        ElementDataType dataType = elementType.getDataType();
        String dbType;
        if (dataType == ElementDataType.array) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.bool) {
            dbType = "INTEGER";
        } else if (dataType == ElementDataType.configpath) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.integer) {
            dbType = "INTEGER";
        } else if (dataType == ElementDataType.number) {
            dbType = "REAL";
        } else if (dataType == ElementDataType.object) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.rowpath) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.string) {
            dbType = "TEXT";
        } else {
            throw new IllegalStateException("unexpected ElementDataType: " + dataType.name());
        }
        //@formatter:off
        createTableCmdWithCols.append(", ").append(column.getElementKey()).append(" ").append(dbType)
                .append(" NULL");
        //@formatter:on
    }

    createTableCmdWithCols.append(");");

    db.execSQL(createTableCmdWithCols.toString());

    // Create the metadata for the table - table def and KVS
    createDBTableMetadata(db, tableId);

    // Now need to call the function to write out all the column values
    for (ColumnDefinition column : orderedDefs) {
        createNewColumnMetadata(db, tableId, column);
    }

    // Need to address column order
    ContentValues cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_COL_ORDER);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "array");

    StringBuilder tableDefCol = new StringBuilder();

    boolean needsComma = false;
    for (ColumnDefinition def : orderedDefs) {
        if (!def.isUnitOfRetention()) {
            continue;
        }
        if (needsComma) {
            tableDefCol.append(",");
        }
        needsComma = true;
        tableDefCol.append("\"").append(def.getElementKey()).append("\"");
    }

    WebLogger.getLogger(appName).i(t, "Column order for table " + tableId + " is " + tableDefCol.toString());
    String colOrderVal = "[" + tableDefCol.toString() + "]";
    cvTableVal.put(KeyValueStoreColumns.VALUE, colOrderVal);

    // Now add Tables values into KVS
    db.replaceOrThrow(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, cvTableVal);
}

From source file:org.path.common.android.utilities.ODKDatabaseUtils.java

public void createDBTableWithColumns(SQLiteDatabase db, String appName, String tableId,
        List<ColumnDefinition> orderedDefs) {
    if (tableId == null || tableId.length() <= 0) {
        throw new IllegalArgumentException(t + ": application name and table name must be specified");
    }//from w ww. j a  v a 2  s . co m

    String createTableCmd = getUserDefinedTableCreationStatement(tableId);

    StringBuilder createTableCmdWithCols = new StringBuilder();
    createTableCmdWithCols.append(createTableCmd);

    for (ColumnDefinition column : orderedDefs) {
        if (!column.isUnitOfRetention()) {
            continue;
        }
        ElementType elementType = column.getType();

        ElementDataType dataType = elementType.getDataType();
        String dbType;
        if (dataType == ElementDataType.array) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.bool) {
            dbType = "INTEGER";
        } else if (dataType == ElementDataType.configpath) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.integer) {
            dbType = "INTEGER";
        } else if (dataType == ElementDataType.number) {
            dbType = "REAL";
        } else if (dataType == ElementDataType.object) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.rowpath) {
            dbType = "TEXT";
        } else if (dataType == ElementDataType.string) {
            dbType = "TEXT";
        } else {
            throw new IllegalStateException("unexpected ElementDataType: " + dataType.name());
        }
        //@formatter:off
        createTableCmdWithCols.append(", ").append(column.getElementKey()).append(" ").append(dbType)
                .append(" NULL");
        //@formatter:on
    }

    createTableCmdWithCols.append(");");

    db.execSQL(createTableCmdWithCols.toString());

    // Create the metadata for the table - table def and KVS
    createDBTableMetadata(db, tableId);

    // Now need to call the function to write out all the column values
    for (ColumnDefinition column : orderedDefs) {
        createNewColumnMetadata(db, tableId, column);
    }

    // Need to address column order
    ContentValues cvTableVal = new ContentValues();
    cvTableVal.put(KeyValueStoreColumns.TABLE_ID, tableId);
    cvTableVal.put(KeyValueStoreColumns.PARTITION, KeyValueStoreConstants.PARTITION_TABLE);
    cvTableVal.put(KeyValueStoreColumns.ASPECT, KeyValueStoreConstants.ASPECT_DEFAULT);
    cvTableVal.put(KeyValueStoreColumns.KEY, KeyValueStoreConstants.TABLE_COL_ORDER);
    cvTableVal.put(KeyValueStoreColumns.VALUE_TYPE, "array");

    StringBuilder tableDefCol = new StringBuilder();

    boolean needsComma = false;
    for (ColumnDefinition def : orderedDefs) {
        if (!def.isUnitOfRetention()) {
            continue;
        }
        if (needsComma) {
            tableDefCol.append(",");
        }
        needsComma = true;
        tableDefCol.append("\"").append(def.getElementKey()).append("\"");
    }

    WebLogger.getLogger(appName).i(t, "Column order for table " + tableId + " is " + tableDefCol.toString());
    String colOrderVal = "[" + tableDefCol.toString() + "]";
    cvTableVal.put(KeyValueStoreColumns.VALUE, colOrderVal);

    // Now add Tables values into KVS
    db.replaceOrThrow(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, cvTableVal);
}