Example usage for android.database.sqlite SQLiteDatabase close

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Releases a reference to the object, closing the object if the last reference was released.

Usage

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

public void loadInitialUnitUsage() {
    final SQLiteDatabase db = getWritableDatabase();
    // load the initial table in
    final ContentValues cv = new ContentValues();

    Log.d(TAG, "init all weights hash");
    final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size());
    Log.d(TAG, "adding all known weights...");
    for (final String unitName : Unit.table.keySet()) {
        // don't add all uppercase names
        if (!unitName.toUpperCase().equals(unitName)) {
            allUnitWeights.put(unitName, 0);
        }/* www . j av a  2s  .c  o  m*/
    }
    Log.d(TAG, "adding all known functions...");
    for (final String functionName : BuiltInFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    //      for (final String functionName: TabularFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    //      for (final String functionName: ComputedFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    for (final String functionName : DefinedFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    Log.d(TAG, "adding common weights");
    addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights);
    Log.d(TAG, "adding regional weights");
    addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights);

    // This is so that things of common weight end up in non-random order
    // without having to do an SQL order-by.
    final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet());
    Log.d(TAG, "Sorting units...");
    Collections.sort(sortedUnits);
    Log.d(TAG, "Adding all sorted units...");

    final HashMap<String, String> fingerprints = loadFingerprints();

    db.beginTransaction();
    for (final String unitName : sortedUnits) {
        cv.put(UsageEntry._UNIT, unitName);
        cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName));

        final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName)
                : getFingerprint(unitName);

        fingerprints.put(unitName, fpr);
        cv.put(UsageEntry._FACTOR_FPRINT, fpr);
        db.insert(DB_USAGE_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

    context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null);

    // If we have the right permissons, save the fingerprints file to a JSON file
    // which can then be imported into the app to speed up initial fingerpint loading.
    if (context.checkCallingOrSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        final File externalStorage = Environment.getExternalStorageDirectory();
        final File fprintsOutput = new File(externalStorage, "units_fingerprints.json");
        final JSONObject jo = new JSONObject(fingerprints);
        try {
            final FileWriter fw = new FileWriter(fprintsOutput);
            fw.write(jo.toString(1));
            fw.close();
            Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath());

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "done!");
}

From source file:net.smart_json_database.JSONDatabase.java

public int insert(JSONEntity entity) {

    int returnValue = -1;
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {//ww  w  .  j  a  va2 s . co  m
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put("createDate", Util.DateToString(entity.getCreationDate()));
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("data", entity.getData().toString());
        values.put("type", entity.getType());
        int uid = Util.LongToInt(db.insert(TABLE_JSON_DATA, null, values));
        returnValue = uid;
        //entity.setUid(uid);
        for (String name : entity.getTags().getToAdd()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                tagid = insertTag(name, db);
            } else {
                tagid = tags.get(name);
            }
            if (relateTagWithJsonEntity(tagid, uid, db) == -1) {
                throw new Exception("could not relate entity with tags");
            }
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            //               for(Integer id : hasMany.getToRemove())
            //               {
            //                  deleteRelation(hasMany.getName(), uid, id, db);
            //               }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), uid, id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            //               for(Integer id : belongsTo.getToRemove())
            //               {
            //                  deleteRelation(belongsTo.getName(), id ,uid,  db);
            //               }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, uid, db);
            }
        }

        db.setTransactionSuccessful();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_INSERT);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

From source file:net.olejon.mdapp.NotesEditActivity.java

private void getNote() {
    if (noteId != 0) {
        SQLiteDatabase sqLiteDatabase = new NotesSQLiteHelper(mContext).getReadableDatabase();

        String[] queryColumns = { NotesSQLiteHelper.COLUMN_TITLE, NotesSQLiteHelper.COLUMN_TEXT,
                NotesSQLiteHelper.COLUMN_PATIENT_ID, NotesSQLiteHelper.COLUMN_PATIENT_NAME,
                NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR, NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT,
                NotesSQLiteHelper.COLUMN_PATIENT_ROOM, NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS };
        Cursor cursor = sqLiteDatabase.query(NotesSQLiteHelper.TABLE, queryColumns,
                NotesSQLiteHelper.COLUMN_ID + " = " + noteId, null, null, null, null);

        if (cursor.moveToFirst()) {
            String title = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TITLE));
            String text = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TEXT));
            String patientId = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ID));
            String patientName = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_NAME));
            String patientDoctor = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR));
            String patientDepartment = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT));
            String patientRoom = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ROOM));
            String patientMedications = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS));

            mTitleEditText.setText(title);
            mTextEditText.setText(text);
            mPatientIdEditText.setText(patientId);
            mPatientNameEditText.setText(patientName);
            mPatientDoctorEditText.setText(patientDoctor);
            mPatientDepartmentEditText.setText(patientDepartment);
            mPatientRoomEditText.setText(patientRoom);

            if (patientMedications != null && !patientMedications.equals("")) {
                try {
                    mPatientMedicationsJsonArray = new JSONArray(patientMedications);

                    getMedications();//w  w w .  ja v  a 2  s. c  o m
                } catch (Exception e) {
                    Log.e("NotesEditActivity", Log.getStackTraceString(e));
                }
            }
        }

        cursor.close();
        sqLiteDatabase.close();
    }
}

From source file:net.olejon.mdapp.MedicationActivity.java

private void favorite() {
    SQLiteDatabase sqLiteDatabase = new MedicationsFavoritesSQLiteHelper(mContext).getWritableDatabase();

    String snackbarString;// www  . j a  va 2s  .  c  o  m

    if (isFavorite()) {
        sqLiteDatabase.delete(MedicationsFavoritesSQLiteHelper.TABLE,
                MedicationsFavoritesSQLiteHelper.COLUMN_NAME + " = " + mTools.sqe(medicationName) + " AND "
                        + MedicationsFavoritesSQLiteHelper.COLUMN_MANUFACTURER + " = "
                        + mTools.sqe(medicationManufacturer),
                null);

        mFavoriteMenuItem.setIcon(R.drawable.ic_star_outline_white_24dp)
                .setTitle(getString(R.string.medication_menu_add_favorite));

        snackbarString = getString(R.string.medication_favorite_removed);
    } else {
        ContentValues contentValues = new ContentValues();

        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_PRESCRIPTION_GROUP,
                medicationPrescriptionGroup);
        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_NAME, medicationName);
        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_SUBSTANCE, medicationSubstance);
        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_MANUFACTURER, medicationManufacturer);

        sqLiteDatabase.insert(MedicationsFavoritesSQLiteHelper.TABLE, null, contentValues);

        Intent intent = new Intent();
        intent.setAction("update");
        mContext.sendBroadcast(intent);

        mFavoriteMenuItem.setIcon(R.drawable.ic_star_white_24dp)
                .setTitle(getString(R.string.medication_menu_remove_favorite));

        snackbarString = getString(R.string.medication_favorite_saved);
    }

    Snackbar snackbar = Snackbar.make(mRelativeLayout, snackbarString, Snackbar.LENGTH_LONG)
            .setAction(R.string.snackbar_undo, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    favorite();
                }
            }).setActionTextColor(ContextCompat.getColor(mContext, R.color.orange));

    View snackbarView = snackbar.getView();

    TextView snackbarTextView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);

    snackbarTextView.setTextColor(ContextCompat.getColor(mContext, R.color.white));

    snackbar.show();

    mTools.updateWidget();

    sqLiteDatabase.close();
}

From source file:com.openerp.orm.ORM.java

/**
 * Write.//from ww  w .  j  a  va  2  s. c o m
 * 
 * @param dbHelper
 *            the db helper
 * @param values
 *            the values
 * @param id
 *            the id
 * @param fromServer
 *            the from server
 * @return true, if successful
 */
public boolean write(BaseDBHelper dbHelper, ContentValues values, int id, boolean fromServer) {

    // Handling many2one records
    HashMap<String, Object> many2onecols = dbHelper.getMany2OneColumns();
    // Handling Many2Many Records
    HashMap<String, Object> many2manycols = dbHelper.getMany2ManyColumns();
    for (String key : many2manycols.keySet()) {
        try {

            JSONArray m2mArray = new JSONArray(values.getAsString(key));
            Many2Many m2m = (Many2Many) many2manycols.get(key);
            updateM2MRecords(values.getAsString("id"), m2mArray, key, dbHelper, m2m, values);
        } catch (Exception e) {

        }
        values.remove(key);
    }
    // Handling many2one records. [id, "name"] to id
    for (String key : many2onecols.keySet()) {
        try {
            String tempVals = values.getAsString(key);
            if (!tempVals.equals("false")) {
                JSONArray m2oArray = new JSONArray(values.getAsString(key));
                int m2oid = m2oArray.getInt(0);
                values.put(key, m2oid);
            } else {
                values.put(key, "false");
            }
        } catch (Exception e) {
        }
    }

    boolean flag = false;
    SQLiteDatabase db = getWritableDatabase();
    try {
        if (OpenERPServerConnection.isNetworkAvailable(context)) {
            String table = modelToTable(dbHelper.getModelName());
            try {

                JSONObject arguments = new JSONObject();
                for (String key : values.keySet()) {
                    try {
                        int keyid = Integer.parseInt(values.getAsString(key));
                        arguments.put(key, keyid);
                    } catch (Exception e) {
                        String temp = values.getAsString(key);
                        if (temp.equals("true") || temp.equals("false")) {
                            arguments.put(key, ((temp.equals("true")) ? true : false));
                        } else {

                            arguments.put(key, values.get(key).toString());

                        }
                    }

                }
                if (fromServer) {
                    int res = db.update(table, values, "id = " + id, null);
                    flag = true;
                } else {

                    if (oe_obj.updateValues(dbHelper.getModelName(), arguments, id)) {
                        int res = db.update(table, values, "id = " + id, null);
                        flag = true;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }

        } else {
            Toast.makeText(context, "Unable to Connect server ! Please Try again Later. ", Toast.LENGTH_LONG)
                    .show();
            flag = false;
        }
    } catch (Exception e) {
    }
    db.close();
    return flag;
}

From source file:net.smart_json_database.JSONDatabase.java

public int update(JSONEntity entity) {
    int returnValue = -1;
    if (entity.getUid() == -1) {
        return returnValue;
    }//  w  ww  .j  a v a2s .c o  m

    SQLiteDatabase db = dbHelper.getWritableDatabase();

    try {
        db.beginTransaction();
        entity.setUpdateDate(new Date());
        ContentValues values = new ContentValues();
        values.put("data", entity.getData().toString());
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("type", entity.getType());
        String[] params = new String[] { "" + entity.getUid() };
        db.update(TABLE_JSON_DATA, values, "json_uid = ?", params);
        for (String name : entity.getTags().getToAdd()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                tagid = insertTag(name, db);
            } else {
                tagid = tags.get(name);
            }
            if (relateTagWithJsonEntity(tagid, entity.getUid(), db) == -1) {
                throw new Exception("could not relate");
            }

        }
        for (String name : entity.getTags().getToRemove()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                continue;
            } else {
                tagid = tags.get(name);
            }

            db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", new String[] { "" + tagid });
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            for (Integer id : hasMany.getToRemove()) {
                deleteRelation(hasMany.getName(), entity.getUid(), id, db);
            }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), entity.getUid(), id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            for (Integer id : belongsTo.getToRemove()) {
                deleteRelation(belongsTo.getName(), id, entity.getUid(), db);
            }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, entity.getUid(), db);
            }
        }

        db.setTransactionSuccessful();
        returnValue = entity.getUid();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_UPDATE);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;

}

From source file:org.opendatakit.sync.ProcessRowDataChanges.java

private UserTable updateLocalRowsFromServerChanges(TableResource tableResource, TableDefinitionEntry te,
        ArrayList<ColumnDefinition> orderedColumns, String displayName, boolean deferInstanceAttachments,
        ArrayList<ColumnDefinition> fileAttachmentColumns, List<SyncRowPending> rowsToPushFileAttachments,
        UserTable localDataTable, RowResourceList rows) throws IOException {

    String tableId = tableResource.getTableId();
    TableResult tableResult = sc.getTableResult(tableId);

    if (rows.getRows().isEmpty()) {
        // nothing here -- let caller determine whether we are done or
        // whether we need to issue another request to the server.
        return localDataTable;
    }//  w w w  .  ja v a2  s  . c  om

    Map<String, SyncRow> changedServerRows = new HashMap<String, SyncRow>();
    for (RowResource row : rows.getRows()) {
        SyncRow syncRow = new SyncRow(row.getRowId(), row.getRowETag(), row.isDeleted(), row.getFormId(),
                row.getLocale(), row.getSavepointType(), row.getSavepointTimestamp(), row.getSavepointCreator(),
                row.getFilterScope(), row.getValues(), fileAttachmentColumns);
        changedServerRows.put(row.getRowId(), syncRow);
    }

    sc.updateNotification(SyncProgressState.ROWS, R.string.anaylzing_row_changes, new Object[] { tableId }, 7.0,
            false);

    /**************************
     * PART 2: UPDATE THE DATA
     **************************/
    log.d(TAG, "updateDbFromServer setServerHadDataChanges(true)");
    tableResult.setServerHadDataChanges(!changedServerRows.isEmpty());
    // these are all the various actions we will need to take:

    // serverRow updated; no matching localRow
    List<SyncRowDataChanges> rowsToInsertLocally = new ArrayList<SyncRowDataChanges>();

    // serverRow updated; localRow SyncState is synced or
    // synced_pending_files
    List<SyncRowDataChanges> rowsToUpdateLocally = new ArrayList<SyncRowDataChanges>();

    // serverRow deleted; localRow SyncState is synced or
    // synced_pending_files
    List<SyncRowDataChanges> rowsToDeleteLocally = new ArrayList<SyncRowDataChanges>();

    // serverRow updated or deleted; localRow SyncState is not synced or
    // synced_pending_files
    List<SyncRowDataChanges> rowsToMoveToInConflictLocally = new ArrayList<SyncRowDataChanges>();

    // loop through the localRow table
    for (int i = 0; i < localDataTable.getNumberOfRows(); i++) {
        Row localRow = localDataTable.getRowAtIndex(i);
        String stateStr = localRow.getRawDataOrMetadataByElementKey(DataTableColumns.SYNC_STATE);
        SyncState state = stateStr == null ? null : SyncState.valueOf(stateStr);

        String rowId = localRow.getRowId();

        // see if there is a change to this row from our current
        // server change set.
        SyncRow serverRow = changedServerRows.get(rowId);

        if (serverRow == null) {
            continue;
        }

        // OK -- the server is reporting a change (in serverRow) to the
        // localRow.
        // if the localRow is already in a in_conflict state, determine
        // what its
        // ConflictType is. If the localRow holds the earlier server-side
        // change,
        // then skip and look at the next record.
        int localRowConflictTypeBeforeSync = -1;
        if (state == SyncState.in_conflict) {
            // we need to remove the in_conflict records that refer to the
            // prior state of the server
            String localRowConflictTypeBeforeSyncStr = localRow
                    .getRawDataOrMetadataByElementKey(DataTableColumns.CONFLICT_TYPE);
            localRowConflictTypeBeforeSync = localRowConflictTypeBeforeSyncStr == null ? null
                    : Integer.parseInt(localRowConflictTypeBeforeSyncStr);
            if (localRowConflictTypeBeforeSync == ConflictType.SERVER_DELETED_OLD_VALUES
                    || localRowConflictTypeBeforeSync == ConflictType.SERVER_UPDATED_UPDATED_VALUES) {
                // This localRow holds the server values from a
                // previously-identified conflict.
                // Skip it -- we will clean up this copy later once we find
                // the matching localRow
                // that holds the locally-changed values that were in conflict
                // with this earlier
                // set of server values.
                continue;
            }
        }

        // remove this server row from the map of changes reported by the
        // server.
        // the following decision tree will always place the row into one
        // of the
        // local action lists.
        changedServerRows.remove(rowId);

        // OK the record is either a simple local record or a local
        // in_conflict record
        if (state == SyncState.synced || state == SyncState.synced_pending_files) {
            // the server's change should be applied locally.
            //
            // the file attachments might be stale locally,
            // but those are dealt with separately.

            if (serverRow.isDeleted()) {
                rowsToDeleteLocally.add(new SyncRowDataChanges(serverRow,
                        SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow),
                        (state == SyncState.synced_pending_files)));
            } else {
                rowsToUpdateLocally.add(new SyncRowDataChanges(serverRow,
                        SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow),
                        (state == SyncState.synced_pending_files)));
            }
        } else if (serverRow.isDeleted() && (state == SyncState.deleted || (state == SyncState.in_conflict
                && localRowConflictTypeBeforeSync == ConflictType.LOCAL_DELETED_OLD_VALUES))) {
            // this occurs if
            // (1) a delete request was never ACKed but it was performed
            // on the server.
            // (2) if there is an unresolved conflict held locally with the
            // local action being to delete the record, and the prior server
            // state being a value change, but the newly sync'd state now
            // reflects a deletion by another party.
            //

            // no need to worry about server in_conflict records.
            // any server in_conflict rows will be deleted during the delete
            // step
            rowsToDeleteLocally.add(new SyncRowDataChanges(serverRow,
                    SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), false));
        } else {
            // SyncState.deleted and server is not deleting
            // SyncState.new_row and record exists on server
            // SyncState.changed and new change on server
            // SyncState.in_conflict and new change on server

            // no need to worry about server in_conflict records.
            // any server in_conflict rows will be cleaned up during the
            // update of the in_conflict state.

            // figure out what the localRow conflict type should be...
            Integer localRowConflictType;
            if (state == SyncState.changed) {
                // SyncState.changed and new change on server
                localRowConflictType = ConflictType.LOCAL_UPDATED_UPDATED_VALUES;
                log.i(TAG, "local row was in sync state CHANGED, changing to "
                        + "IN_CONFLICT and setting conflict type to: " + localRowConflictType);
            } else if (state == SyncState.new_row) {
                // SyncState.new_row and record exists on server
                // The 'new_row' case occurs if an insert is never ACKed but
                // completes successfully on the server.
                localRowConflictType = ConflictType.LOCAL_UPDATED_UPDATED_VALUES;
                log.i(TAG, "local row was in sync state NEW_ROW, changing to "
                        + "IN_CONFLICT and setting conflict type to: " + localRowConflictType);
            } else if (state == SyncState.deleted) {
                // SyncState.deleted and server is not deleting
                localRowConflictType = ConflictType.LOCAL_DELETED_OLD_VALUES;
                log.i(TAG, "local row was in sync state DELETED, changing to "
                        + "IN_CONFLICT and updating conflict type to: " + localRowConflictType);
            } else if (state == SyncState.in_conflict) {
                // SyncState.in_conflict and new change on server
                // leave the local conflict type unchanged (retrieve it and
                // use it).
                localRowConflictType = localRowConflictTypeBeforeSync;
                log.i(TAG,
                        "local row was in sync state IN_CONFLICT, leaving as "
                                + "IN_CONFLICT and leaving conflict type unchanged as: "
                                + localRowConflictTypeBeforeSync);
            } else {
                throw new IllegalStateException("Unexpected state encountered");
            }
            SyncRowDataChanges syncRow = new SyncRowDataChanges(serverRow,
                    SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), false,
                    localRowConflictType);

            if (!syncRow.identicalValues(orderedColumns)) {
                if (syncRow.identicalValuesExceptRowETagAndFilterScope(orderedColumns)) {
                    // just apply the server RowETag and filterScope to the
                    // local row
                    rowsToUpdateLocally.add(new SyncRowDataChanges(serverRow,
                            SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), true));
                } else {
                    rowsToMoveToInConflictLocally.add(syncRow);
                }
            } else {
                log.w(TAG, "identical rows returned from server -- SHOULDN'T THESE NOT HAPPEN?");
            }
        }
    }

    // Now, go through the remaining serverRows in the rows map. That
    // map now contains only row changes that don't affect any existing
    // localRow. If the server change is not a row-deletion / revoke-row
    // action, then insert the serverRow locally.
    for (SyncRow serverRow : changedServerRows.values()) {
        boolean isDeleted = serverRow.isDeleted();
        if (!isDeleted) {
            rowsToInsertLocally.add(new SyncRowDataChanges(serverRow, null, false));
        }
    }

    //
    // OK we have captured the local inserting, locally updating,
    // locally deleting and conflicting actions. And we know
    // the changes for the server. Determine the per-row percentage
    // for applying all these changes

    int totalChange = rowsToInsertLocally.size() + rowsToUpdateLocally.size() + rowsToDeleteLocally.size()
            + rowsToMoveToInConflictLocally.size();

    perRowIncrement = 70.0 / ((double) (totalChange + 1));
    rowsProcessed = 0;
    boolean hasAttachments = !fileAttachmentColumns.isEmpty();

    // i.e., we have created entries in the various action lists
    // for all the actions we should take.

    // ///////////////////////////////////////////////////
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES
    // / PERFORM LOCAL DATABASE CHANGES

    {
        SQLiteDatabase db = null;
        try {
            db = sc.getDatabase();

            // this will individually move some files to the locally-deleted state
            // if we cannot sync file attachments in those rows.
            pushLocalAttachmentsBeforeDeleteRowsInDb(db, tableResource, rowsToDeleteLocally,
                    fileAttachmentColumns, deferInstanceAttachments, tableResult);

            // and now do a big transaction to update the local database.
            db.beginTransaction();

            deleteRowsInDb(db, tableResource, rowsToDeleteLocally, fileAttachmentColumns,
                    deferInstanceAttachments, tableResult);

            insertRowsInDb(db, tableResource, orderedColumns, rowsToInsertLocally, rowsToPushFileAttachments,
                    hasAttachments, tableResult);

            updateRowsInDb(db, tableResource, orderedColumns, rowsToUpdateLocally, rowsToPushFileAttachments,
                    hasAttachments, tableResult);

            conflictRowsInDb(db, tableResource, orderedColumns, rowsToMoveToInConflictLocally,
                    rowsToPushFileAttachments, hasAttachments, tableResult);

            localDataTable = ODKDatabaseUtils.get().rawSqlQuery(db, sc.getAppName(), tableId, orderedColumns,
                    null, null, null, null, DataTableColumns.ID, "ASC");

            // TODO: fix this for synced_pending_files
            // We likely need to relax this constraint on the
            // server?

            db.setTransactionSuccessful();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
                db = null;
            }
        }
    }

    return localDataTable;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public MessageArrayContent[] getMessages(String buddyId, int amount, int offset, boolean reverse) {
    //Log.d("DATABASE", "Getting messages");
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
            MessageHistoryContract.MessageEntry._ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
    Cursor messages = db.query(buddyId, columns, null, null, null, null,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP + " DESC", offset + "," + amount);

    if (reverse)// ww w  .  j  a v  a2  s .  c  o  m
        messages.moveToFirst();
    else
        messages.moveToLast();
    int messageCount = messages.getCount();
    MessageArrayContent[] result = new MessageArrayContent[messageCount];
    int i = 0;
    if (messages.getCount() > 0)
        do {
            String from = messages.getString(0);
            SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
            String me = preferences.getString(Constants.USERNAME, "");
            String type = messages.getString(1);
            String content = messages.getString(2);
            String url = messages.getString(3);
            int progress = 0;
            String status = messages.getString(4);
            long time = messages.getLong(5);
            long _ID = messages.getLong(6);
            long othersId = messages.getLong(7);
            switch (type) {
            case (MessageHistory.TYPE_TEXT):
                result[i] = new TextMessage(!me.equals(from), content, time, status, _ID, othersId);
                //            if (((TextMessage) result[i]).left)
                //              updateMessageStatus(from, _ID, STATUS_READ);
                break;
            case (MessageHistory.TYPE_IMAGE):
                try {
                    JSONArray contentJSON = new JSONArray(content);
                    result[i] = new ImageMessage(!me.equals(from), //left
                            contentJSON.getString(0), //File
                            contentJSON.getString(1), //description
                            url, //url
                            progress, //progress
                            time, //timeStamp
                            status, //status
                            _ID, //_ID
                            buddyId, //buddyID
                            othersId); //othersId
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            i++;
        } while (messages.move((reverse) ? 1 : -1));
    db.close();
    messages.close();
    return result;
}

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

public boolean getDummy() {
    // marron power
    SQLiteDatabase db = getReadableDatabase();
    //        db.execSQL("select * from users where user_id = -1");
    db.close();
    return dummyDB;
}