Example usage for android.database.sqlite SQLiteDatabase compileStatement

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

Introduction

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

Prototype

public SQLiteStatement compileStatement(String sql) throws SQLException 

Source Link

Document

Compiles an SQL statement into a reusable pre-compiled statement object.

Usage

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from  w  ww .  j a va  2 s .c  om
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else if (jsonparams[i].isNull(j)) {
                        myStatement.bindNull(j + 1);
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from   w  w  w. ja v  a2 s  .c o m
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:org.kontalk.provider.UsersProvider.java

private int insertKeys(ContentValues[] values) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    int rows = 0;
    SQLiteStatement stm = db.compileStatement("INSERT OR REPLACE INTO " + TABLE_KEYS + " (" + Keys.JID + ", "
            + Keys.FINGERPRINT + ") VALUES(?, ?)");

    for (ContentValues v : values) {
        try {/*from ww  w .j  av  a  2  s .  c o  m*/
            stm.bindString(1, v.getAsString(Keys.JID));
            stm.bindString(2, v.getAsString(Keys.FINGERPRINT));
            stm.executeInsert();
            rows++;
        } catch (SQLException e) {
            Log.w(SyncAdapter.TAG, "error inserting trusted key [" + v + "]", e);
        }
    }

    return rows;
}

From source file:org.kontalk.provider.UsersProvider.java

private int executeUpdateDelete(SQLiteDatabase db, SQLiteStatement stm) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        return stm.executeUpdateDelete();
    } else {//from www  .  java 2s.c o m
        stm.execute();
        SQLiteStatement changes = db.compileStatement("SELECT changes()");
        try {
            return (int) changes.simpleQueryForLong();
        } finally {
            changes.close();
        }
    }
}

From source file:org.kontalk.provider.UsersProvider.java

/** Triggers a complete resync of the users database. */
private int resync() {
    Context context = getContext();
    ContentResolver cr = context.getContentResolver();
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    // begin transaction
    beginTransaction(db);//from  www . j  a  v a2 s  . c  o  m
    boolean success = false;

    int count = 0;

    // delete old users content
    try {
        db.execSQL("DELETE FROM " + TABLE_USERS_OFFLINE);
    } catch (SQLException e) {
        // table might not exist - create it! (shouldn't happen since version 4)
        db.execSQL(DatabaseHelper.SCHEMA_USERS_OFFLINE);
    }

    // we are trying to be fast here
    SQLiteStatement stm = db.compileStatement("INSERT INTO " + TABLE_USERS_OFFLINE
            + " (number, jid, display_name, lookup_key, contact_id, registered)" + " VALUES(?, ?, ?, ?, ?, ?)");

    // these two statements are used to immediately update data in the online table
    // even if the data is dummy, it will be soon replaced by sync or by manual request
    SQLiteStatement onlineUpd = db.compileStatement("UPDATE " + TABLE_USERS
            + " SET number = ?, display_name = ?, lookup_key = ?, contact_id = ? WHERE jid = ?");
    SQLiteStatement onlineIns = db.compileStatement("INSERT INTO " + TABLE_USERS
            + " (number, jid, display_name, lookup_key, contact_id, registered)" + " VALUES(?, ?, ?, ?, ?, ?)");

    Cursor phones = null;
    String dialPrefix = Preferences.getDialPrefix();
    int dialPrefixLen = dialPrefix != null ? dialPrefix.length() : 0;

    try {
        String where = !Preferences.getSyncInvisibleContacts(context)
                ? ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1 AND "
                : "";

        // query for phone numbers
        phones = cr.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.DISPLAY_NAME, Phone.LOOKUP_KEY,
                Phone.CONTACT_ID, RawContacts.ACCOUNT_TYPE }, where + " (" +
        // this will filter out RawContacts from Kontalk
                        RawContacts.ACCOUNT_TYPE + " IS NULL OR " + RawContacts.ACCOUNT_TYPE
                        + " NOT IN (?, ?))",
                new String[] { Authenticator.ACCOUNT_TYPE, Authenticator.ACCOUNT_TYPE_LEGACY }, null);

        if (phones != null) {
            while (phones.moveToNext()) {
                String number = phones.getString(0);
                String name = phones.getString(1);

                // buggy provider - skip entry
                if (name == null || number == null)
                    continue;

                // remove dial prefix first
                if (dialPrefix != null && number.startsWith(dialPrefix))
                    number = number.substring(dialPrefixLen);

                // a phone number with less than 4 digits???
                if (number.length() < 4)
                    continue;

                // fix number
                try {
                    number = NumberValidator.fixNumber(context, number,
                            Authenticator.getDefaultAccountName(context), 0);
                } catch (Exception e) {
                    Log.e(SyncAdapter.TAG, "unable to normalize number: " + number + " - skipping", e);
                    // skip number
                    continue;
                }

                try {
                    String hash = MessageUtils.sha1(number);
                    String lookupKey = phones.getString(2);
                    long contactId = phones.getLong(3);
                    String jid = XMPPUtils.createLocalJID(getContext(), hash);

                    addResyncContact(db, stm, onlineUpd, onlineIns, number, jid, name, lookupKey, contactId,
                            false);
                    count++;
                } catch (IllegalArgumentException iae) {
                    Log.w(SyncAdapter.TAG, "doing sync with no server?");
                } catch (SQLiteConstraintException sqe) {
                    // skip duplicate number
                }
            }

            phones.close();
        } else {
            Log.e(SyncAdapter.TAG, "query to contacts failed!");
        }

        if (Preferences.getSyncSIMContacts(getContext())) {
            // query for SIM contacts
            // column selection doesn't work because of a bug in Android
            // TODO this is a bit unclear...
            try {
                phones = cr.query(Uri.parse("content://icc/adn/"), null, null, null, null);
            } catch (Exception e) {
                /*
                On some phones:
                java.lang.NullPointerException
                at android.os.Parcel.readException(Parcel.java:1431)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
                at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
                at android.content.ContentResolver.query(ContentResolver.java:372)
                at android.content.ContentResolver.query(ContentResolver.java:315)
                 */
                Log.w(SyncAdapter.TAG, "unable to retrieve SIM contacts", e);
                phones = null;
            }

            if (phones != null) {
                while (phones.moveToNext()) {
                    String name = phones.getString(phones.getColumnIndex("name"));
                    String number = phones.getString(phones.getColumnIndex("number"));
                    // buggy firmware - skip entry
                    if (name == null || number == null)
                        continue;

                    // remove dial prefix first
                    if (dialPrefix != null && number.startsWith(dialPrefix))
                        number = number.substring(dialPrefixLen);

                    // a phone number with less than 4 digits???
                    if (number.length() < 4)
                        continue;

                    // fix number
                    try {
                        number = NumberValidator.fixNumber(context, number,
                                Authenticator.getDefaultAccountName(context), 0);
                    } catch (Exception e) {
                        Log.e(SyncAdapter.TAG, "unable to normalize number: " + number + " - skipping", e);
                        // skip number
                        continue;
                    }

                    try {
                        String hash = MessageUtils.sha1(number);
                        String jid = XMPPUtils.createLocalJID(getContext(), hash);
                        long contactId = phones.getLong(phones.getColumnIndex(BaseColumns._ID));

                        addResyncContact(db, stm, onlineUpd, onlineIns, number, jid, name, null, contactId,
                                false);
                        count++;
                    } catch (IllegalArgumentException iae) {
                        Log.w(SyncAdapter.TAG, "doing sync with no server?");
                    } catch (SQLiteConstraintException sqe) {
                        // skip duplicate number
                    }
                }
            }
        }

        // try to add account number with display name
        String ownNumber = Authenticator.getDefaultAccountName(getContext());
        if (ownNumber != null) {
            String ownName = Authenticator.getDefaultDisplayName(getContext());
            String fingerprint = null;
            byte[] publicKeyData = null;
            try {
                PersonalKey myKey = Kontalk.get(getContext()).getPersonalKey();
                if (myKey != null) {
                    fingerprint = myKey.getFingerprint();
                    publicKeyData = myKey.getEncodedPublicKeyRing();
                }
            } catch (Exception e) {
                Log.w(SyncAdapter.TAG, "unable to load personal key", e);
            }
            try {
                String hash = MessageUtils.sha1(ownNumber);
                String jid = XMPPUtils.createLocalJID(getContext(), hash);

                addResyncContact(db, stm, onlineUpd, onlineIns, ownNumber, jid, ownName, null, null, true);
                insertOrUpdateKey(jid, fingerprint, publicKeyData, false);
                count++;
            } catch (IllegalArgumentException iae) {
                Log.w(SyncAdapter.TAG, "doing sync with no server?");
            } catch (SQLiteConstraintException sqe) {
                // skip duplicate number
            }
        }

        success = setTransactionSuccessful(db);
    } finally {
        endTransaction(db, success);
        if (phones != null)
            phones.close();
        stm.close();

        // time to invalidate contacts cache (because of updates to online)
        Contact.invalidate();
    }
    return count;
}

From source file:com.newsrob.EntryManager.java

private void deleteArticlesFromDb(final SyncJob job, final List<String> articleIdsToDeleteInDatabase) {
    if (articleIdsToDeleteInDatabase.isEmpty())
        return;/*from   w  w  w  . j  ava2  s  .  com*/

    Timing t2 = new Timing("Delete Articles From Db", ctx);

    job.setJobDescription("Cleaning up database");
    job.target = articleIdsToDeleteInDatabase.size();
    job.actual = 0;
    fireStatusUpdated();

    SQLiteDatabase db = databaseHelper.getDb();

    final String sql1 = "DELETE FROM " + Entries.TABLE_NAME + " WHERE " + Entries.__ID + "=?;";
    final String sql2 = "DELETE FROM " + EntryLabelAssociations.TABLE_NAME + " WHERE "
            + EntryLabelAssociations.ENTRY_ID + "=?;";

    final SQLiteStatement stmt1 = db.compileStatement(sql1);
    final SQLiteStatement stmt2 = db.compileStatement(sql2);

    try {

        // outter loop does the chunking and holds the transaction context
        while (!articleIdsToDeleteInDatabase.isEmpty()) {

            db.beginTransaction();

            while (!articleIdsToDeleteInDatabase.isEmpty()) {

                String id = articleIdsToDeleteInDatabase.remove(0);
                stmt1.bindString(1, id);
                stmt1.execute();
                stmt2.bindString(1, id);
                stmt2.execute();

                job.actual++;

                if (job.actual % 10 == 0)
                    fireStatusUpdated();

                // commit every 35 articles
                if (job.actual >= 35)
                    break;
            }

            db.setTransactionSuccessful();
            db.endTransaction();
        }
    } finally {
        stmt1.close();
        stmt2.close();
    }
    fireStatusUpdated();
    t2.stop();
}

From source file:com.grazerss.EntryManager.java

private void deleteArticlesFromDb(final SyncJob job, final List<String> articleIdsToDeleteInDatabase) {
    if (articleIdsToDeleteInDatabase.isEmpty()) {
        return;/*from   w ww . ja  va 2 s  .  c  o  m*/
    }

    Timing t2 = new Timing("Delete Articles From Db", ctx);

    job.setJobDescription("Cleaning up database");
    job.target = articleIdsToDeleteInDatabase.size();
    job.actual = 0;
    fireStatusUpdated();

    SQLiteDatabase db = databaseHelper.getDb();

    final String sql1 = "DELETE FROM " + Entries.TABLE_NAME + " WHERE " + Entries.__ID + "=?;";
    final String sql2 = "DELETE FROM " + EntryLabelAssociations.TABLE_NAME + " WHERE "
            + EntryLabelAssociations.ENTRY_ID + "=?;";

    final SQLiteStatement stmt1 = db.compileStatement(sql1);
    final SQLiteStatement stmt2 = db.compileStatement(sql2);

    try {

        // outter loop does the chunking and holds the transaction context
        while (!articleIdsToDeleteInDatabase.isEmpty()) {

            db.beginTransaction();

            while (!articleIdsToDeleteInDatabase.isEmpty()) {

                String id = articleIdsToDeleteInDatabase.remove(0);
                stmt1.bindString(1, id);
                stmt1.execute();
                stmt2.bindString(1, id);
                stmt2.execute();

                job.actual++;

                if ((job.actual % 10) == 0) {
                    fireStatusUpdated();
                }

                // commit every 35 articles
                if (job.actual >= 35) {
                    break;
                }
            }

            db.setTransactionSuccessful();
            db.endTransaction();
        }
    } finally {
        stmt1.close();
        stmt2.close();
    }
    fireStatusUpdated();
    t2.stop();
}

From source file:org.ttrssreader.controllers.DBHelper.java

@SuppressWarnings("deprecation")
private synchronized boolean initializeDBHelper() {
    final Context context = contextRef.get();
    if (context == null) {
        Log.e(TAG, "Can't handle internal DB without Context-Object.");
        return false;
    }/* w  ww .  ja  va2 s. co m*/

    if (getOpenHelper() != null)
        closeDB();

    openHelper = new OpenHelper(context);
    SQLiteDatabase db = openHelper.getWritableDatabase();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
        db.setLockingEnabled(true);

    if (specialUpgradeSuccessful) {
        // Re-open DB for final usage:
        closeDB();
        openHelper = new OpenHelper(context);
        db = openHelper.getWritableDatabase();

        Toast.makeText(context, "ImageCache is beeing cleaned...", Toast.LENGTH_LONG).show();
        new org.ttrssreader.utils.AsyncTask<Void, Void, Void>() {
            protected Void doInBackground(Void... params) {
                // Clear ImageCache since no files are in REMOTE_FILES anymore and we dont want to leave them
                // there forever:
                ImageCache imageCache = Controller.getInstance().getImageCache();
                imageCache.fillMemoryCacheFromDisk();
                File cacheFolder = new File(imageCache.getDiskCacheDirectory());
                if (cacheFolder.isDirectory()) {
                    try {
                        FileUtils.deleteDirectory(cacheFolder);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            protected void onPostExecute(Void result) {
                Toast.makeText(context, "ImageCache has been cleaned up...", Toast.LENGTH_LONG).show();
            }
        }.execute();
    }

    insertCategory = db.compileStatement(INSERT_CATEGORY);
    insertFeed = db.compileStatement(INSERT_FEED);
    insertArticle = db.compileStatement(INSERT_ARTICLE);
    insertLabel = db.compileStatement(INSERT_LABEL);
    insertRemoteFile = db.compileStatement(INSERT_REMOTEFILE);
    insertRemoteFile2Article = db.compileStatement(INSERT_REMOTEFILE2ARTICLE);

    db.acquireReference();
    initialized = true;
    return true;
}

From source file:mobile.tiis.appv2.base.BackboneApplication.java

public void updateChildVaccinationEventVaccinationAppointment(ChildCollector childCollector) {
    Child child = childCollector.getChildEntity();
    List<VaccinationEvent> vaccinationEvents = childCollector.getVeList();
    List<VaccinationAppointment> vaccinationAppointments = childCollector.getVaList();
    ContentValues childCV = new ContentValues();
    DatabaseHandler db = getDatabaseInstance();

    SQLiteDatabase db1 = db.getWritableDatabase();
    db1.beginTransactionNonExclusive();/*  ww w  .ja  v  a 2s. co m*/
    try {
        String sql0 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.CHILD + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.ChildColumns.ID + ","
                + SQLHandler.ChildColumns.BARCODE_ID + "," + SQLHandler.ChildColumns.FIRSTNAME1 + ","
                + SQLHandler.ChildColumns.FIRSTNAME2 + "," + SQLHandler.ChildColumns.LASTNAME1 + ","
                + SQLHandler.ChildColumns.BIRTHDATE + "," + SQLHandler.ChildColumns.GENDER + ","
                + SQLHandler.ChildColumns.TEMP_ID + "," + SQLHandler.ChildColumns.HEALTH_FACILITY + ","
                + SQLHandler.ChildColumns.DOMICILE + "," + SQLHandler.ChildColumns.DOMICILE_ID + ","
                + SQLHandler.ChildColumns.HEALTH_FACILITY_ID + "," + SQLHandler.ChildColumns.STATUS_ID + ","
                + SQLHandler.ChildColumns.BIRTHPLACE_ID + "," + SQLHandler.ChildColumns.NOTES + ","
                + SQLHandler.ChildColumns.STATUS + "," + SQLHandler.ChildColumns.MOTHER_FIRSTNAME + ","
                + SQLHandler.ChildColumns.MOTHER_LASTNAME + ","
                + SQLHandler.ChildColumns.CUMULATIVE_SERIAL_NUMBER + ","
                + SQLHandler.ChildColumns.CHILD_REGISTRY_YEAR + "," + SQLHandler.ChildColumns.MOTHER_TT2_STS
                + "," + SQLHandler.ChildColumns.MOTHER_VVU_STS + "," + SQLHandler.ChildColumns.PHONE
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt0 = db1.compileStatement(sql0);
        stmt0.bindString(1, "1");
        stmt0.bindString(2, child.getId() == null ? "" : child.getId());
        stmt0.bindString(3, child.getBarcodeID() == null ? "" : child.getBarcodeID());
        stmt0.bindString(4, child.getFirstname1() == null ? "" : child.getFirstname1());
        stmt0.bindString(5, child.getFirstname2() == null ? "" : child.getFirstname2());
        stmt0.bindString(6, child.getLastname1() == null ? "" : child.getLastname1());
        stmt0.bindString(7, child.getBirthdate() == null ? "" : child.getBirthdate());
        stmt0.bindString(8, child.getGender() == null ? "" : child.getGender());
        stmt0.bindString(9, child.getTempId() == null ? "" : child.getTempId());
        stmt0.bindString(10, child.getHealthcenter() == null ? "" : child.getHealthcenter());
        stmt0.bindString(11, child.getDomicile() == null ? "" : child.getDomicile());
        stmt0.bindString(12, child.getDomicileId() == null ? "" : child.getDomicileId());
        stmt0.bindString(13, child.getHealthcenterId() == null ? "" : child.getHealthcenterId());
        stmt0.bindString(14, child.getStatusId() == null ? "" : child.getStatusId());
        stmt0.bindString(15, child.getBirthplaceId() == null ? "" : child.getBirthplaceId());
        stmt0.bindString(16, child.getNotes() == null ? "" : child.getNotes());
        stmt0.bindString(17, child.getStatus() == null ? "" : child.getStatus());
        stmt0.bindString(18, child.getMotherFirstname() == null ? "" : child.getMotherFirstname());
        stmt0.bindString(19, child.getMotherLastname() == null ? "" : child.getMotherLastname());
        stmt0.bindString(20, child.getChildCumulativeSn() == null ? "" : child.getChildCumulativeSn());
        stmt0.bindString(21, child.getChildRegistryYear() == null ? "" : child.getChildRegistryYear());
        stmt0.bindString(22, child.getMotherTT2Status() == null ? "" : child.getMotherTT2Status());
        stmt0.bindString(23, child.getMotherHivStatus() == null ? "" : child.getMotherHivStatus());
        stmt0.bindString(24, child.getPhone() == null ? "" : child.getPhone());
        stmt0.execute();
        stmt0.clearBindings();

        String sql = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_EVENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationEventColumns.APPOINTMENT_ID
                + "," + SQLHandler.VaccinationEventColumns.CHILD_ID + ","
                + SQLHandler.VaccinationEventColumns.DOSE_ID + ","
                + SQLHandler.VaccinationEventColumns.HEALTH_FACILITY_ID + ","
                + SQLHandler.VaccinationEventColumns.ID + "," + SQLHandler.VaccinationEventColumns.IS_ACTIVE
                + "," + SQLHandler.VaccinationEventColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationEventColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationEventColumns.NONVACCINATION_REASON_ID + ","
                + SQLHandler.VaccinationEventColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_STATUS + ","
                + SQLHandler.VaccinationEventColumns.VACCINE_LOT_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt = db1.compileStatement(sql);

        for (VaccinationEvent vaccinationEvent : vaccinationEvents) {
            stmt.bindString(1, "1");
            stmt.bindString(2, vaccinationEvent.getAppointmentId());
            stmt.bindString(3, vaccinationEvent.getChildId());
            stmt.bindString(4, vaccinationEvent.getDoseId());
            stmt.bindString(5, vaccinationEvent.getHealthFacilityId());
            stmt.bindString(6, vaccinationEvent.getId());
            stmt.bindString(7, vaccinationEvent.getIsActive());
            stmt.bindString(8, vaccinationEvent.getModifiedBy());
            stmt.bindString(9, vaccinationEvent.getModifiedOn());
            stmt.bindString(10, vaccinationEvent.getNonvaccinationReasonId());
            stmt.bindString(11, vaccinationEvent.getScheduledDate());
            stmt.bindString(12, vaccinationEvent.getVaccinationDate());
            stmt.bindString(13, vaccinationEvent.getVaccinationStatus());
            stmt.bindString(14, vaccinationEvent.getVaccineLotId());
            stmt.execute();
            stmt.clearBindings();
        }

        String sql1 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_APPOINTMENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationAppointmentColumns.CHILD_ID
                + "," + SQLHandler.VaccinationAppointmentColumns.ID + ","
                + SQLHandler.VaccinationAppointmentColumns.IS_ACTIVE + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationAppointmentColumns.NOTES + ","
                + SQLHandler.VaccinationAppointmentColumns.OUTREACH + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_FACILITY_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";

        SQLiteStatement stmt1 = db1.compileStatement(sql1);

        for (VaccinationAppointment vaccinationAppointment : vaccinationAppointments) {
            stmt1.bindString(1, "1");
            stmt1.bindString(2, vaccinationAppointment.getChildId());
            stmt1.bindString(3, vaccinationAppointment.getId());
            stmt1.bindString(4, vaccinationAppointment.getIsActive());
            stmt1.bindString(5, vaccinationAppointment.getModifiedBy());
            stmt1.bindString(6, vaccinationAppointment.getModifiedOn());
            stmt1.bindString(7, vaccinationAppointment.getNotes());
            stmt1.bindString(8, vaccinationAppointment.getOutreach());
            stmt1.bindString(9, vaccinationAppointment.getScheduledDate());
            stmt1.bindString(10, vaccinationAppointment.getScheduledFacilityId());

            stmt1.execute();
            stmt1.clearBindings();

        }

        db1.setTransactionSuccessful();
        db1.endTransaction();
    } catch (Exception e) {
        db1.endTransaction();
        e.printStackTrace();
    }
}

From source file:mobile.tiis.appv2.base.BackboneApplication.java

/**
 * method used to add child, vaccination appointments and vaccination events into the database
 *
 * @param childCollector/*from  w  w  w  .j av  a2 s  .  co m*/
 */
public void addChildVaccinationEventVaccinationAppointment(ChildCollector childCollector) {
    Child child = childCollector.getChildEntity();
    List<VaccinationEvent> vaccinationEvents = childCollector.getVeList();
    List<VaccinationAppointment> vaccinationAppointments = childCollector.getVaList();
    ContentValues childCV = new ContentValues();
    DatabaseHandler db = getDatabaseInstance();

    SQLiteDatabase db1 = db.getWritableDatabase();
    db1.beginTransactionNonExclusive();
    try {
        String sql0 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.CHILD + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.ChildColumns.ID + ","
                + SQLHandler.ChildColumns.BARCODE_ID + "," + SQLHandler.ChildColumns.FIRSTNAME1 + ","
                + SQLHandler.ChildColumns.FIRSTNAME2 + "," + SQLHandler.ChildColumns.LASTNAME1 + ","
                + SQLHandler.ChildColumns.BIRTHDATE + "," + SQLHandler.ChildColumns.GENDER + ","
                + SQLHandler.ChildColumns.TEMP_ID + "," + SQLHandler.ChildColumns.HEALTH_FACILITY + ","
                + SQLHandler.ChildColumns.DOMICILE + "," + SQLHandler.ChildColumns.DOMICILE_ID + ","
                + SQLHandler.ChildColumns.HEALTH_FACILITY_ID + "," + SQLHandler.ChildColumns.STATUS_ID + ","
                + SQLHandler.ChildColumns.BIRTHPLACE_ID + "," + SQLHandler.ChildColumns.NOTES + ","
                + SQLHandler.ChildColumns.STATUS + "," + SQLHandler.ChildColumns.MOTHER_FIRSTNAME + ","
                + SQLHandler.ChildColumns.MOTHER_LASTNAME + ","
                + SQLHandler.ChildColumns.CUMULATIVE_SERIAL_NUMBER + ","
                + SQLHandler.ChildColumns.CHILD_REGISTRY_YEAR + "," + SQLHandler.ChildColumns.MOTHER_TT2_STS
                + "," + SQLHandler.ChildColumns.MOTHER_VVU_STS + "," + SQLHandler.ChildColumns.PHONE
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt0 = db1.compileStatement(sql0);
        stmt0.bindString(1, "1");
        stmt0.bindString(2, child.getId() == null ? "" : child.getId());
        stmt0.bindString(3, child.getBarcodeID() == null ? "" : child.getBarcodeID());
        stmt0.bindString(4, child.getFirstname1() == null ? "" : child.getFirstname1());
        stmt0.bindString(5, child.getFirstname2() == null ? "" : child.getFirstname2());
        stmt0.bindString(6, child.getLastname1() == null ? "" : child.getLastname1());
        stmt0.bindString(7, child.getBirthdate() == null ? "" : child.getBirthdate());
        stmt0.bindString(8, child.getGender() == null ? "" : child.getGender());
        stmt0.bindString(9, child.getTempId() == null ? "" : child.getTempId());
        stmt0.bindString(10, child.getHealthcenter() == null ? "" : child.getHealthcenter());
        stmt0.bindString(11, child.getDomicile() == null ? "" : child.getDomicile());
        stmt0.bindString(12, child.getDomicileId() == null ? "" : child.getDomicileId());
        stmt0.bindString(13, child.getHealthcenterId() == null ? "" : child.getHealthcenterId());
        stmt0.bindString(14, child.getStatusId() == null ? "" : child.getStatusId());
        stmt0.bindString(15, child.getBirthplaceId() == null ? "" : child.getBirthplaceId());
        stmt0.bindString(16, child.getNotes() == null ? "" : child.getNotes());
        stmt0.bindString(17, child.getStatus() == null ? "" : child.getStatus());
        stmt0.bindString(18, child.getMotherFirstname() == null ? "" : child.getMotherFirstname());
        stmt0.bindString(19, child.getMotherLastname() == null ? "" : child.getMotherLastname());
        stmt0.bindString(20, child.getChildCumulativeSn() == null ? "" : child.getChildCumulativeSn());
        stmt0.bindString(21, child.getChildRegistryYear() == null ? "" : child.getChildRegistryYear());
        stmt0.bindString(22, child.getMotherTT2Status() == null ? "" : child.getMotherTT2Status());
        stmt0.bindString(23, child.getMotherHivStatus() == null ? "" : child.getMotherHivStatus());
        stmt0.bindString(24, child.getPhone() == null ? "" : child.getPhone());
        stmt0.execute();
        stmt0.clearBindings();

        String sql = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_EVENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationEventColumns.APPOINTMENT_ID
                + "," + SQLHandler.VaccinationEventColumns.CHILD_ID + ","
                + SQLHandler.VaccinationEventColumns.DOSE_ID + ","
                + SQLHandler.VaccinationEventColumns.HEALTH_FACILITY_ID + ","
                + SQLHandler.VaccinationEventColumns.ID + "," + SQLHandler.VaccinationEventColumns.IS_ACTIVE
                + "," + SQLHandler.VaccinationEventColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationEventColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationEventColumns.NONVACCINATION_REASON_ID + ","
                + SQLHandler.VaccinationEventColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_STATUS + ","
                + SQLHandler.VaccinationEventColumns.VACCINE_LOT_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt = db1.compileStatement(sql);

        for (VaccinationEvent vaccinationEvent : vaccinationEvents) {
            stmt.bindString(1, "1");
            stmt.bindString(2, vaccinationEvent.getAppointmentId());
            stmt.bindString(3, vaccinationEvent.getChildId());
            stmt.bindString(4, vaccinationEvent.getDoseId());
            stmt.bindString(5, vaccinationEvent.getHealthFacilityId());
            stmt.bindString(6, vaccinationEvent.getId());
            stmt.bindString(7, vaccinationEvent.getIsActive());
            stmt.bindString(8, vaccinationEvent.getModifiedBy());
            stmt.bindString(9, vaccinationEvent.getModifiedOn());
            stmt.bindString(10, vaccinationEvent.getNonvaccinationReasonId());
            stmt.bindString(11, vaccinationEvent.getScheduledDate());
            stmt.bindString(12, vaccinationEvent.getVaccinationDate());
            stmt.bindString(13, vaccinationEvent.getVaccinationStatus());
            stmt.bindString(14, vaccinationEvent.getVaccineLotId());
            stmt.execute();
            stmt.clearBindings();
        }

        String sql1 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_APPOINTMENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationAppointmentColumns.CHILD_ID
                + "," + SQLHandler.VaccinationAppointmentColumns.ID + ","
                + SQLHandler.VaccinationAppointmentColumns.IS_ACTIVE + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationAppointmentColumns.NOTES + ","
                + SQLHandler.VaccinationAppointmentColumns.OUTREACH + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_FACILITY_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";

        SQLiteStatement stmt1 = db1.compileStatement(sql1);

        for (VaccinationAppointment vaccinationAppointment : vaccinationAppointments) {
            stmt1.bindString(1, "1");
            stmt1.bindString(2, vaccinationAppointment.getChildId());
            stmt1.bindString(3, vaccinationAppointment.getId());
            stmt1.bindString(4, vaccinationAppointment.getIsActive());
            stmt1.bindString(5, vaccinationAppointment.getModifiedBy());
            stmt1.bindString(6, vaccinationAppointment.getModifiedOn());
            stmt1.bindString(7, vaccinationAppointment.getNotes());
            stmt1.bindString(8, vaccinationAppointment.getOutreach());
            stmt1.bindString(9, vaccinationAppointment.getScheduledDate());
            stmt1.bindString(10, vaccinationAppointment.getScheduledFacilityId());

            stmt1.execute();
            stmt1.clearBindings();

        }

        db1.setTransactionSuccessful();
        db1.endTransaction();
    } catch (Exception e) {
        db1.endTransaction();
        e.printStackTrace();
    }
}