List of usage examples for android.database.sqlite SQLiteDatabase close
public void close()
From source file:net.potterpcs.recipebook.RecipeData.java
public int insertRecipe(Recipe r) { synchronized (DB_LOCK) { SQLiteDatabase db = dbHelper.getWritableDatabase(); int ret = -1; try {/*from w w w.j a v a 2 s.co m*/ ContentValues values = createRecipeForInsert(r); long rowid = db.insert(RECIPES_TABLE, null, values); if (r.ingredients != null) { for (String ing : r.ingredients) { ContentValues cvi = createIngredientsCV(rowid, ing); db.insertWithOnConflict(INGREDIENTS_TABLE, null, cvi, SQLiteDatabase.CONFLICT_IGNORE); } } if (r.directions != null) { int step = 1; for (String dir : r.directions) { ContentValues cdirs = createDirectionsCV(rowid, step, dir, r.directions_photos[step - 1]); db.insertWithOnConflict(DIRECTIONS_TABLE, null, cdirs, SQLiteDatabase.CONFLICT_IGNORE); step++; } } if (r.tags != null) { for (String tag : r.tags) { ContentValues ctags = createTagsCV(rowid, tag); db.insertWithOnConflict(TAGS_TABLE, null, ctags, SQLiteDatabase.CONFLICT_IGNORE); } } ret = (int) rowid; } finally { db.close(); } return ret; } }
From source file:org.opendatakit.sync.ProcessRowDataChanges.java
/** * Synchronize the table data rows./*from w ww. j av a2 s. co m*/ * <p> * Note that if the db changes under you when calling this method, the tp * parameter will become out of date. It should be refreshed after calling * this method. * <p> * This method does NOT synchronize any non-instance files; it assumes the * database schema has already been sync'd. * * @param tableResource * the table resource from the server, either from the getTables() * call or from a createTable() response. * @param te * definition of the table to synchronize * @param orderedColumns * well-formed ordered list of columns in this table. * @param displayName * display name for this tableId - used in notifications * @param deferInstanceAttachments * true if new instance attachments should NOT be pulled from or * pushed to the server. e.g., for bandwidth management. */ private void synchronizeTableDataRowsAndAttachments(TableResource tableResource, TableDefinitionEntry te, ArrayList<ColumnDefinition> orderedColumns, String displayName, boolean deferInstanceAttachments) { boolean attachmentSyncSuccessful = false; boolean rowDataSyncSuccessful = false; ArrayList<ColumnDefinition> fileAttachmentColumns = new ArrayList<ColumnDefinition>(); for (ColumnDefinition cd : orderedColumns) { if (cd.getType().getDataType() == ElementDataType.rowpath) { fileAttachmentColumns.add(cd); } } log.i(TAG, "synchronizeTableDataRowsAndAttachments - deferInstanceAttachments: " + Boolean.toString(deferInstanceAttachments)); // Prepare the tableResult. We'll start it as failure, and only update it // if we're successful at the end. String tableId = te.getTableId(); TableResult tableResult = sc.getTableResult(tableId); tableResult.setTableDisplayName(displayName); if (tableResult.getStatus() != Status.WORKING) { // there was some sort of error... log.e(TAG, "Skipping data sync - error in table schema or file verification step " + tableId); return; } if (tableId.equals("framework")) { // do not sync the framework table tableResult.setStatus(Status.SUCCESS); sc.updateNotification(SyncProgressState.ROWS, R.string.table_data_sync_complete, new Object[] { tableId }, 100.0, false); return; } boolean containsConflicts = false; try { log.i(TAG, "REST " + tableId); int passNumber = 1; while (passNumber <= 2) { // reset the table status to working... tableResult.resetStatus(); tableResult.setMessage((passNumber == 1) ? "beginning row data sync" : "retrying row data sync"); ++passNumber; sc.updateNotification(SyncProgressState.ROWS, R.string.verifying_table_schema_on_server, new Object[] { tableId }, 0.0, false); // test that the schemaETag matches // if it doesn't, the user MUST sync app-level files and // configuration // syncing at the app level will adjust/set the local table // properties // schemaETag to match that on the server. String schemaETag = te.getSchemaETag(); if (schemaETag == null || !tableResource.getSchemaETag().equals(schemaETag)) { // schemaETag is not identical tableResult.setServerHadSchemaChanges(true); tableResult.setMessage( "Server schemaETag differs! Sync app-level files and configuration in order to sync this table."); tableResult.setStatus(Status.TABLE_REQUIRES_APP_LEVEL_SYNC); return; } // file attachments we should sync with the server... List<SyncRowPending> rowsToPushFileAttachments = new ArrayList<SyncRowPending>(); boolean updateToServerSuccessful = false; for (; !updateToServerSuccessful;) { updateToServerSuccessful = false; // always start with an empty synced-pending-files list. rowsToPushFileAttachments.clear(); try { // ////////////////////////////////////////////////// // ////////////////////////////////////////////////// // get all the rows in the data table -- we will iterate through // them all. UserTable localDataTable; { SQLiteDatabase db = null; try { db = sc.getDatabase(); localDataTable = ODKDatabaseUtils.get().rawSqlQuery(db, sc.getAppName(), tableId, orderedColumns, null, null, null, null, DataTableColumns.ID, "ASC"); } finally { if (db != null) { db.close(); db = null; } } } containsConflicts = localDataTable.hasConflictRows(); // ////////////////////////////////////////////////// // ////////////////////////////////////////////////// // fail the sync on this table if there are checkpoint rows. if (localDataTable.hasCheckpointRows()) { // should only be reachable on the first time through this for // loop... tableResult.setMessage(sc.getString(R.string.table_contains_checkpoints)); tableResult.setStatus(Status.TABLE_CONTAINS_CHECKPOINTS); return; } // ////////////////////////////////////////////////// // ////////////////////////////////////////////////// // Pull changes from the server... tableResult.setPulledServerData(false); sc.updateNotification(SyncProgressState.ROWS, R.string.getting_changed_rows_on_server, new Object[] { tableId }, 5.0, false); boolean pullCompletedSuccessfully = false; String firstDataETag = null; String websafeResumeCursor = null; for (;;) { RowResourceList rows = null; try { rows = sc.getSynchronizer().getUpdates(tableResource, te.getLastDataETag(), websafeResumeCursor); if (firstDataETag == null) { firstDataETag = rows.getDataETag(); } } catch (ClientWebException e) { if (e.getResponse() != null && e.getResponse().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { clientAuthException("synchronizeTable - pulling data down from server", tableId, e, tableResult); } else { clientWebException("synchronizeTable - pulling data down from server", tableId, e, tableResult); } break; } catch (InvalidAuthTokenException e) { clientAuthException("synchronizeTable - pulling data down from server", tableId, e, tableResult); break; } catch (Exception e) { exception("synchronizeTable - pulling data down from server", tableId, e, tableResult); break; } localDataTable = updateLocalRowsFromServerChanges(tableResource, te, orderedColumns, displayName, deferInstanceAttachments, fileAttachmentColumns, rowsToPushFileAttachments, localDataTable, rows); if (rows.isHasMoreResults()) { websafeResumeCursor = rows.getWebSafeResumeCursor(); } else { // //////////////////////////////// // //////////////////////////////// // Success // // We have to update our dataETag here so that the server // knows we saw its changes. Otherwise it won't let us // put up new information. // // Note that we may have additional changes from // subsequent dataETags (changeSets). We only // break out of this loop if the dataETag on the // last request matches the firstDataETag. Otherwise, // we re-issue a fetch using the firstDataETag as // a starting point. { SQLiteDatabase db = null; try { db = sc.getDatabase(); // update the dataETag to the one returned by the first // of the fetch queries, above. ODKDatabaseUtils.get().updateDBTableETags(db, tableId, tableResource.getSchemaETag(), firstDataETag); // and be sure to update our in-memory objects... te.setSchemaETag(tableResource.getSchemaETag()); te.setLastDataETag(firstDataETag); tableResource.setDataETag(firstDataETag); } finally { if (db != null) { db.close(); db = null; } } } if ((firstDataETag == null) ? (rows.getDataETag() != null) : !firstDataETag.equals(rows.getDataETag())) { // re-issue request... websafeResumeCursor = null; } else { // success -- exit the update loop... pullCompletedSuccessfully = true; break; } } } // If we made it here and there was data, then we successfully // updated the localDataTable from the server. tableResult.setPulledServerData(pullCompletedSuccessfully); if (!pullCompletedSuccessfully) { break; } // //////////////////////////////// // //////////////////////////////// // OK. We can now scan through the localDataTable for changes that // should be sent up to the server. sc.updateNotification(SyncProgressState.ROWS, R.string.anaylzing_row_changes, new Object[] { tableId }, 70.0, false); /************************** * PART 2: UPDATE THE DATA **************************/ // these are all the various actions we will need to take: // localRow SyncState.new_row no changes pulled from server // localRow SyncState.changed no changes pulled from server // localRow SyncState.deleted no changes pulled from server List<SyncRow> allAlteredRows = new ArrayList<SyncRow>(); // 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(); // the local row wasn't impacted by a server change // see if this local row should be pushed to the server. if (state == SyncState.new_row || state == SyncState.changed || state == SyncState.deleted) { allAlteredRows.add( SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow)); } else if (state == SyncState.synced_pending_files) { rowsToPushFileAttachments.add(new SyncRowPending( SyncRow.convertToSyncRow(orderedColumns, fileAttachmentColumns, localRow), false, true, true)); } } // We know the changes for the server. Determine the per-row // percentage for applying all these changes int totalChange = allAlteredRows.size() + rowsToPushFileAttachments.size(); perRowIncrement = 90.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. // ///////////////////////////////////// // SERVER CHANGES // SERVER CHANGES // SERVER CHANGES // SERVER CHANGES // SERVER CHANGES // SERVER CHANGES if (allAlteredRows.size() != 0) { tableResult.setHadLocalDataChanges(true); } // idempotent interface means that the interactions // for inserts, updates and deletes are identical. int count = 0; ArrayList<RowOutcome> specialCases = new ArrayList<RowOutcome>(); if (!allAlteredRows.isEmpty()) { int offset = 0; while (offset < allAlteredRows.size()) { // alter UPSERT_BATCH_SIZE rows at a time to the server int max = offset + UPSERT_BATCH_SIZE; if (max > allAlteredRows.size()) { max = allAlteredRows.size(); } List<SyncRow> segmentAlter = allAlteredRows.subList(offset, max); RowOutcomeList outcomes = sc.getSynchronizer().alterRows(tableResource, segmentAlter); if (outcomes.getRows().size() != segmentAlter.size()) { throw new IllegalStateException("Unexpected partial return?"); } // process outcomes... count = processRowOutcomes(te, tableResource, tableResult, orderedColumns, fileAttachmentColumns, hasAttachments, rowsToPushFileAttachments, count, allAlteredRows.size(), segmentAlter, outcomes.getRows(), specialCases); // NOTE: specialCases should probably be deleted? // This is the case if the user doesn't have permissions... // TODO: figure out whether these are benign or need // reporting.... if (!specialCases.isEmpty()) { throw new IllegalStateException( "update request rejected by the server -- do you have table synchronize privileges?"); } // update our dataETag. Because the server will have failed with // a CONFLICT (409) if our dataETag did not match ours at the // time the update occurs, we are assured that there are no // interleaved changes we are unaware of. { SQLiteDatabase db = null; try { db = sc.getDatabase(); // update the dataETag to the one returned by the first // of the fetch queries, above. ODKDatabaseUtils.get().updateDBTableETags(db, tableId, tableResource.getSchemaETag(), outcomes.getDataETag()); // and be sure to update our in-memory objects... te.setSchemaETag(tableResource.getSchemaETag()); te.setLastDataETag(outcomes.getDataETag()); tableResource.setDataETag(outcomes.getDataETag()); } finally { if (db != null) { db.close(); db = null; } } } // process next segment... offset = max; } } // And now update that we've pushed our changes to the server. tableResult.setPushedLocalData(true); // OK. Now we have pushed everything. // because of the 409 (CONFLICT) alterRows enforcement on the // server, we know that our data records are consistent and // our processing is complete. updateToServerSuccessful = true; } catch (ClientWebException e) { if (e.getResponse().getStatusCode() == HttpStatus.SC_CONFLICT) { // expected -- there were row updates by another client // re-pull changes from the server. Return to the start // of the for(;;) loop. continue; } // otherwise it is an error... if (e.getResponse() != null && e.getResponse().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { clientAuthException("synchronizeTable - pushing data up to server", tableId, e, tableResult); } else { clientWebException("synchronizeTable - pushing data up to server", tableId, e, tableResult); } break; } catch (InvalidAuthTokenException e) { clientAuthException("synchronizeTable - pushing data up to server", tableId, e, tableResult); break; } catch (Exception e) { exception("synchronizeTable - pushing data up to server", tableId, e, tableResult); break; } } // done with rowData sync. Either we were successful, or // there was an error. If there was an error, we will // try once more in the outer loop. rowDataSyncSuccessful = updateToServerSuccessful; // Our update may not have been successful. Only push files if it was... if (rowDataSyncSuccessful) { try { attachmentSyncSuccessful = (rowsToPushFileAttachments.isEmpty()); // And try to push the file attachments... int count = 0; boolean attachmentSyncFailed = false; for (SyncRowPending syncRowPending : rowsToPushFileAttachments) { boolean outcome = true; if (!syncRowPending.onlyGetFiles()) { outcome = sc.getSynchronizer().putFileAttachments( tableResource.getInstanceFilesUri(), tableId, syncRowPending, deferInstanceAttachments); } if (outcome) { outcome = sc.getSynchronizer().getFileAttachments( tableResource.getInstanceFilesUri(), tableId, syncRowPending, deferInstanceAttachments); if (syncRowPending.updateSyncState()) { if (outcome) { // OK -- we succeeded in putting/getting all attachments // update our state to the synced state. SQLiteDatabase db = null; try { db = sc.getDatabase(); ODKDatabaseUtils.get().updateRowETagAndSyncState(db, tableId, syncRowPending.getRowId(), syncRowPending.getRowETag(), SyncState.synced); } finally { if (db != null) { db.close(); db = null; } } } else { // only care about instance file status if we are trying // to update state attachmentSyncFailed = false; } } } tableResult.incLocalAttachmentRetries(); ++count; ++rowsProcessed; if (rowsProcessed % ROWS_BETWEEN_PROGRESS_UPDATES == 0) { sc.updateNotification(SyncProgressState.ROWS, R.string.uploading_attachments_server_row, new Object[] { tableId, count, rowsToPushFileAttachments.size() }, 10.0 + rowsProcessed * perRowIncrement, false); } } attachmentSyncSuccessful = !attachmentSyncFailed; } catch (ClientWebException e) { if (e.getResponse() != null && e.getResponse().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { clientAuthException("synchronizeTable - auth error synchronizing attachments", tableId, e, tableResult); log.e(TAG, "[synchronizeTableRest] auth failure synchronizing attachments " + e.toString()); } else { clientWebException("synchronizeTableRest", tableId, e, tableResult); log.e(TAG, "[synchronizeTableRest] error synchronizing attachments " + e.toString()); } } catch (Exception e) { exception("synchronizeTableRest", tableId, e, tableResult); log.e(TAG, "[synchronizeTableRest] error synchronizing attachments " + e.toString()); } } if (rowDataSyncSuccessful && attachmentSyncSuccessful) { // no need to retry... break; } } if (rowDataSyncSuccessful) { // if the row data was sync'd // update the last-sync-time // NOTE: disregard whether // attachments were successfully // sync'd. SQLiteDatabase db = null; try { db = sc.getDatabase(); ODKDatabaseUtils.get().updateDBTableLastSyncTime(db, tableId); } finally { if (db != null) { db.close(); db = null; } } } } finally { // Here we also want to add the TableResult to the value. if (rowDataSyncSuccessful) { // Then we should have updated the db and shouldn't have set the // TableResult to be exception. if (tableResult.getStatus() != Status.WORKING) { log.e(TAG, "tableResult status for table: " + tableId + " was " + tableResult.getStatus().name() + ", and yet success returned true. This shouldn't be possible."); } else { if (containsConflicts) { tableResult.setStatus(Status.TABLE_CONTAINS_CONFLICTS); sc.updateNotification(SyncProgressState.ROWS, R.string.table_data_sync_with_conflicts, new Object[] { tableId }, 100.0, false); } else if (!attachmentSyncSuccessful) { tableResult.setStatus(Status.TABLE_PENDING_ATTACHMENTS); sc.updateNotification(SyncProgressState.ROWS, R.string.table_data_sync_pending_attachments, new Object[] { tableId }, 100.0, false); } else { tableResult.setStatus(Status.SUCCESS); sc.updateNotification(SyncProgressState.ROWS, R.string.table_data_sync_complete, new Object[] { tableId }, 100.0, false); } } } } }
From source file:com.HskPackage.HskNamespace.HSK1ProjectActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);/*from w ww . j a v a 2 s.co m*/ final TextView codice = (TextView) findViewById(R.id.codice); final Button carattere = (Button) findViewById(R.id.carattere); final TextView fonetica = (TextView) findViewById(R.id.fonetica); final TextView significato = (TextView) findViewById(R.id.significato); /*********** CREATE A DATABASE ******************************************************/ final String DB_PATH = "/data/data/com.HskPackage.HskNamespace/"; final String DB_NAME = "chineseX.db"; SQLiteDatabase db = null; boolean exists = (new File(DB_PATH + DB_NAME)).exists(); AssetManager assetManager = getAssets(); if (!exists) { try { InputStream in = assetManager.open(DB_NAME); OutputStream out = new FileOutputStream(DB_PATH + DB_NAME); copyFile(in, out); in.close(); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } File dbFile = new File(DB_PATH + DB_NAME); db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); } else { File dbFile = new File(DB_PATH + DB_NAME); db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); } final Integer valore = 1; //String query = "SELECT * FROM chineseX"; String query = "SELECT * FROM chineseX where _id = ? "; String[] selectionArgs = { valore.toString() }; Cursor cursor = null; cursor = db.rawQuery(query, selectionArgs); //cursor = db.rawQuery(query, null); int count = cursor.getCount(); System.out.println("il numero di dati contenuti nel database " + count); while (cursor.moveToNext()) { long id = cursor.getLong(0); System.out.println("Questo l'ID ====>" + id); scodice = cursor.getString(1); codice.setText(scodice); System.out.println("Questo il codice ====>" + codice); scarattere = cursor.getString(2); carattere.setText(scarattere); System.out.println("Questo il carattere ====>" + carattere); sfonetica = cursor.getString(3); fonetica.setText(sfonetica); System.out.println("Questo il fonet ====>" + fonetica); ssignificato = cursor.getString(4); significato.setText("?? - Visualizza Significato"); System.out.println("Questo il carattere ====>" + ssignificato); } //fine db.close(); //set up sound button final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.hangout_ringtone); //final MediaPlayer chword001 = MediaPlayer.create(this, R.raw.ayi001); /* // set up change Images miaImmagine = (ImageView) findViewById(R.id.Image); // dichiaro l'oggetto image view miaImmagine.setImageResource(R.drawable.uno1); // associo l'immagine alla figura uno // setto un evento di cattura del click sull'immagine miaImmagine.setOnClickListener( new OnClickListener() { public void onClick(View arg0) { //chword001.start(); } }) ; */ final Intent first = new Intent(this, Activity2.class); final Intent immagine = new Intent(this, Activity3.class); /* * Un intent definito nella javadoc della classe android.content.Intent come una * "descrizione astratta dell'operazione da eseguire". * E un intent ESPLICITO perch cosciamo il destinatario. * Passiamo come parametri il context attuale ed la classe che identifica l'activity di destinazione. * E' importante che la classe sia registrata nell'AndroidManifest.xml * */ Button b = (Button) this.findViewById(R.id.button1); Button b2 = (Button) this.findViewById(R.id.button2); Button b3 = (Button) this.findViewById(R.id.carattere); b.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Integer valore = 1; valore = valore + 1; if (valore >= 153) { valore = 1; } System.out.println("AVANTI" + valore); first.putExtra("AVANTI", valore); startActivity(first); finish(); mpButtonClick.start(); } }); b2.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Integer valore = 153; System.out.println("AVANTI == >" + valore); first.putExtra("AVANTI", valore); startActivity(first); finish(); mpButtonClick.start(); } }); b3.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Integer valore = 1; System.out.println("AVANTI" + valore); immagine.putExtra("AVANTI", valore); startActivity(immagine); finish(); mpButtonClick.start(); } }); }
From source file:com.openerp.orm.ORM.java
public List<HashMap<String, Object>> executeSQL(String sqlQuery, String[] args) { SQLiteDatabase db = getWritableDatabase(); List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); Cursor cursor = db.rawQuery(sqlQuery.toString(), args); String[] columns = cursor.getColumnNames(); if (cursor.moveToFirst()) { do {//from ww w .j av a2 s . c o m HashMap<String, Object> row = new HashMap<String, Object>(); if (cursor.getColumnIndex("oea_name") > 0) { if (!cursor.getString(cursor.getColumnIndex("oea_name")).equals(user_name)) { continue; } } else { Log.e("ORM::executeSQL() - Column name missing", "You must have to provide oea_name column in your sql syntax."); return null; } for (String key : columns) { row.put(key, cursor.getString(cursor.getColumnIndex(key))); } data.add(row); } while (cursor.moveToNext()); } db.close(); cursor.close(); return data; }
From source file:com.odoo.orm.OModel.java
/** * Select m2 m records./*from w w w .ja v a2 s . c om*/ * * @param base * the base * @param rel * the rel * @param base_id * the base_id * @return the list */ public List<ODataRow> selectM2MRecords(OModel base, OModel rel, int base_id) { List<ODataRow> records = new ArrayList<ODataRow>(); String table = base.getTableName() + "_" + rel.getTableName() + "_rel"; String base_col = base.getTableName() + "_id"; String rel_col = rel.getTableName() + "_id"; SQLiteDatabase db = getReadableDatabase(); String where = base_col + " = ? and odoo_name = ?"; Object[] whereArgs = new Object[] { base_id, mUser.getAndroidName() }; Cursor cr = db.query(table, new String[] { "*" }, getWhereClause(where), getWhereArgs(where, whereArgs), null, null, null); List<Integer> ids = new ArrayList<Integer>(); if (cr.moveToFirst()) { do { int rel_id = cr.getInt(cr.getColumnIndex(rel_col)); ids.add(rel_id); } while (cr.moveToNext()); } cr.close(); db.close(); records.addAll(rel.select(OColumn.ROW_ID + " IN (" + StringUtils.repeat(" ?, ", ids.size() - 1) + "?)", new Object[] { ids })); return records; }
From source file:net.potterpcs.recipebook.RecipeData.java
public int updateRecipe(Recipe r) { synchronized (DB_LOCK) { SQLiteDatabase db = dbHelper.getWritableDatabase(); int ret = -1; try {//from w ww .j a v a2 s .c om long rid = r.id; String[] whereArgs = { Long.toString(rid) }; ret = db.update(RECIPES_TABLE, createRecipeForInsert(r), RT_ID + " = ?", new String[] { Long.toString(r.id) }); // TODO until we can figure out a smarter way to update db.delete(INGREDIENTS_TABLE, IT_RECIPE_ID + " = ?", whereArgs); for (String ing : r.ingredients) { db.insertWithOnConflict(INGREDIENTS_TABLE, null, createIngredientsCV(rid, ing), SQLiteDatabase.CONFLICT_IGNORE); } db.delete(DIRECTIONS_TABLE, DT_RECIPE_ID + " = ?", whereArgs); int step = 1; for (String dir : r.directions) { db.insertWithOnConflict(DIRECTIONS_TABLE, null, createDirectionsCV(rid, step, dir, r.directions_photos[step - 1]), SQLiteDatabase.CONFLICT_IGNORE); step++; } db.delete(TAGS_TABLE, TT_RECIPE_ID + " = ?", whereArgs); for (String tag : r.tags) { db.insertWithOnConflict(TAGS_TABLE, null, createTagsCV(rid, tag), SQLiteDatabase.CONFLICT_IGNORE); } } finally { db.close(); } return ret; } }
From source file:io.vit.vitio.Managers.ConnectDatabase.java
public void saveCourses(List<Course> courses) { try {// w w w . j ava 2s. c o m SQLiteDatabase db = this.getWritableDatabase(); for (int i = 0; i < courses.size(); i++) { Course course = courses.get(i); ContentValues values = new ContentValues(); values.put(COLUMNS[0], course.getCLASS_NUMBER()); values.put(COLUMNS[1], course.getCOURSE_TITLE()); values.put(COLUMNS[2], course.getCOURSE_SLOT()); values.put(COLUMNS[3], course.getCOURSE_TYPE()); values.put(COLUMNS[4], course.getCOURSE_TYPE_SHORT()); Log.d("type", course.getCOURSE_TYPE_SHORT()); values.put(COLUMNS[5], course.getCOURSE_LTPC().toString()); values.put(COLUMNS[6], course.getCOURSE_CODE()); values.put(COLUMNS[7], course.getCOURSE_MODE()); values.put(COLUMNS[8], course.getCOURSE_OPTION()); values.put(COLUMNS[9], course.getCOURSE_VENUE()); values.put(COLUMNS[10], course.getCOURSE_FACULTY().toString()); values.put(COLUMNS[11], course.getCOURSE_REGISTRATIONSTATUS()); values.put(COLUMNS[12], course.getCOURSE_BILL_DATE()); values.put(COLUMNS[13], course.getCOURSE_BILL_NUMBER()); values.put(COLUMNS[14], course.getCOURSE_PROJECT_TITLE()); values.put(COLUMNS[15], course.getCOURSE_JSON().toString()); values.put(COLUMNS[16], course.getCOURSE_ATTENDANCE().getJson().toString()); values.put(COLUMNS[17], course.getCOURSE_JSON().getJSONArray("timings").toString()); values.put(COLUMNS[18], course.getCOURSE_JSON().getJSONObject("marks").toString()); //db.insertWithOnConflict(TABLE_COURSES, null, values, SQLiteDatabase.CONFLICT_REPLACE); if (check()) { Log.d("update", "check()"); //onUpgrade(db,db.getVersion(),192564); db.replace(TABLE_COURSES, null, values); //db.update(TABLE_COURSES, values, null, null); } else { Log.d("insert", "check()"); db.insert(TABLE_COURSES, null, values); } } db.close(); } catch (Exception e) { e.printStackTrace(); SQLiteDatabase _db = this.getWritableDatabase(); if (_db != null && _db.isOpen()) { _db.close(); } } }
From source file:com.odoo.orm.OModel.java
/** * Select many to many rel ids./*from w w w . j a va 2s . co m*/ * * @param base * the base * @param rel * the rel * @param base_id * the base_id * @return the list */ public List<Integer> selectM2MRelIds(OModel base, OModel rel, int base_id) { List<Integer> ids = new ArrayList<Integer>(); String table = base.getTableName() + "_" + rel.getTableName() + "_rel"; String base_col = base.getTableName() + "_id"; String rel_col = rel.getTableName() + "_id"; SQLiteDatabase db = getReadableDatabase(); String where = base_col + " = ? and odoo_name = ?"; Object[] whereArgs = new Object[] { base_id, mUser.getAndroidName() }; Cursor cr = db.query(table, new String[] { "*" }, getWhereClause(where), getWhereArgs(where, whereArgs), null, null, null); if (cr.moveToFirst()) { do { int rel_id = cr.getInt(cr.getColumnIndex(rel_col)); if (rel.count(OColumn.ROW_ID + " = ?", new Object[] { rel_id }) > 0) ids.add(rel_id); } while (cr.moveToNext()); } cr.close(); db.close(); return ids; }
From source file:com.spoiledmilk.ibikecph.util.DB.java
public SearchListItem getSearchHistoryByName(String name) { SearchListItem ret = null;/*www . j a v a2s .co m*/ SQLiteDatabase db = getReadableDatabase(); if (db == null) return null; String[] columns = { KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_START_DATE, KEY_END_DATE, KEY_SOURCE, KEY_SUBSOURCE, KEY_LAT, KEY_LONG }; Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, KEY_NAME + " = ? ", new String[] { name.trim() }, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { while (cursor != null && !cursor.isAfterLast()) { int colId = cursor.getColumnIndex(KEY_ID); int colName = cursor.getColumnIndex(KEY_NAME); int colAddress = cursor.getColumnIndex(KEY_ADDRESS); int colStartDate = cursor.getColumnIndex(KEY_START_DATE); int colEndDate = cursor.getColumnIndex(KEY_END_DATE); int colSource = cursor.getColumnIndex(KEY_SOURCE); int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE); int colLat = cursor.getColumnIndex(KEY_LAT); int colLong = cursor.getColumnIndex(KEY_LONG); HistoryData hd = new HistoryData(cursor.getInt(colId), cursor.getString(colName), cursor.getString(colAddress), cursor.getString(colStartDate), cursor.getString(colEndDate), cursor.getString(colSource), cursor.getString(colSubSource), cursor.getDouble(colLat), cursor.getDouble(colLong)); if (hd.getName() != null && !hd.getName().trim().equals("")) { ret = hd; } break; } } if (cursor != null) cursor.close(); db.close(); return ret; }
From source file:com.odoo.orm.OModel.java
public List<ODataRow> query(String sql, String[] args, Boolean closeConnection) { List<ODataRow> records = new ArrayList<ODataRow>(); SQLiteDatabase db = getReadableDatabase(); Cursor cr = db.rawQuery(sql, args); if (cr.moveToFirst()) { do {//from www .ja v a 2 s. c om ODataRow row = createRowFromCursor(cr); if (mWithFunctionalColumns) { for (OColumn col : mFunctionalColumns) { if (!col.canFunctionalStore()) { row.put(col.getName(), getFunctionalMethodValue(col, row)); } } } records.add(row); } while (cr.moveToNext()); } cr.close(); if (closeConnection) db.close(); return records; }