List of usage examples for android.database.sqlite SQLiteDatabase insert
public long insert(String table, String nullColumnHack, ContentValues values)
From source file:net.smart_json_database.JSONDatabase.java
public int insert(JSONEntity entity) { int returnValue = -1; SQLiteDatabase db = dbHelper.getWritableDatabase(); try {/* w w w. j a v a 2s. c om*/ 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:com.spoiledmilk.ibikecph.util.DB.java
public long saveFavorite(FavoritesData fd, Context context, boolean spawnThread) { SQLiteDatabase db = this.getWritableDatabase(); if (db == null) { LOG.e("db is null in saveFavorite"); return -1; }/*from w w w. jav a 2 s .co m*/ long id; ContentValues values = new ContentValues(); values.put(KEY_NAME, fd.getName()); values.put(KEY_ADDRESS, fd.getAdress()); values.put(KEY_SOURCE, fd.getSource()); values.put(KEY_SUBSOURCE, fd.getSubSource()); values.put(KEY_LAT, Double.valueOf(fd.getLatitude())); values.put(KEY_LONG, Double.valueOf(fd.getLongitude())); values.put(KEY_API_ID, fd.getApiId()); id = db.insert(TABLE_FAVORITES, null, values); fd.setId(id); db.close(); if (context != null) { postFavoriteToServer(fd, context, spawnThread); } return id; }
From source file:org.totschnig.myexpenses.provider.TransactionDatabase.java
/** * @param db insert the predefined payment methods in the database, all of them are valid only for bank accounts *//* w w w . j av a2 s . com*/ private void insertDefaultPaymentMethods(SQLiteDatabase db) { ContentValues initialValues; long _id; for (PaymentMethod.PreDefined pm : PaymentMethod.PreDefined.values()) { initialValues = new ContentValues(); initialValues.put(KEY_LABEL, pm.name()); initialValues.put(KEY_TYPE, pm.paymentType); initialValues.put(KEY_IS_NUMBERED, pm.isNumbered); _id = db.insert(TABLE_METHODS, null, initialValues); initialValues = new ContentValues(); initialValues.put(KEY_METHODID, _id); initialValues.put(KEY_TYPE, "BANK"); db.insert(TABLE_ACCOUNTTYES_METHODS, null, initialValues); } }
From source file:com.appmanager.parimal.activity.MainActivity.java
private void loadApps() { manager = this.getPackageManager(); apps = new ArrayList<AppDetail>(); Intent i = new Intent(Intent.ACTION_MAIN, null); i.addCategory(Intent.CATEGORY_LAUNCHER); AppEntryDBHelper mDbHelper = new AppEntryDBHelper(getApplicationContext()); SQLiteDatabase db = mDbHelper.getWritableDatabase(); List<ResolveInfo> availableActivities = manager.queryIntentActivities(i, 0); for (ResolveInfo ri : availableActivities) { if (!ri.activityInfo.packageName.matches("com.appmanager.parimal")) { AppDetail app = new AppDetail(); app.setLabel(ri.loadLabel(manager)); app.setName(ri.activityInfo.packageName); app.setIcon(ri.activityInfo.loadIcon(manager)); apps.add(app);//from w w w . j av a 2 s. com ContentValues values = new ContentValues(); values.put(AppsReaderContract.AppEntry.COLUMN_APP_NAME, ri.loadLabel(manager).toString()); values.put(AppsReaderContract.AppEntry.COLUMN_APP_PACKAGE, ri.activityInfo.packageName); values.put(AppsReaderContract.AppEntry.COLUMN_APP_CATEGORY, "Uncategorized"); values.put(AppsReaderContract.AppEntry.COLUMN_APP_PIN, "0000"); values.put(AppsReaderContract.AppEntry.COLUMN_APP_PIN_USE, "false"); values.put(AppsReaderContract.AppEntry.COLUMN_APP_USAGE, "0"); long newRowId; newRowId = db.insert(AppsReaderContract.AppEntry.TABLE_NAME, null, values); } } db.close(); }
From source file:org.runnerup.export.SyncManager.java
private void syncOK(Synchronizer synchronizer, ProgressDialog copySpinner, SQLiteDatabase copyDB, long id) { copySpinner.setMessage(getResources().getString(R.string.Saving)); ContentValues tmp = new ContentValues(); tmp.put(DB.EXPORT.ACCOUNT, synchronizer.getId()); tmp.put(DB.EXPORT.ACTIVITY, id);// w w w.j a v a2 s . com tmp.put(DB.EXPORT.STATUS, 0); copyDB.insert(DB.EXPORT.TABLE, null, tmp); }
From source file:org.ohmage.db.DbHelper.java
/** * Used by the ContentProvider to insert a campaign and also insert into * interested tables. Don't use this directly; if you do, none of the * contentobservers, etc. that are listening to Campaigns, Surveys, or * SurveyPrompts will be notified./*from www .ja v a 2 s .c o m*/ * * @param values * a ContentValues collection, preferably generated by calling * {@link Campaign}'s toCV() method * @return the ID of the inserted record */ public long addCampaign(SQLiteDatabase db, ContentValues values) { long rowId = -1; // the row ID for the campaign that we'll eventually be // returning try { // start the transaction that will include inserting the campaign + // surveys + survey prompts db.beginTransaction(); // hold onto some variables for processing String configurationXml = values.getAsString(Campaigns.CAMPAIGN_CONFIGURATION_XML); String campaignUrn = values.getAsString(Campaigns.CAMPAIGN_URN); // actually insert the campaign rowId = db.insert(Tables.CAMPAIGNS, null, values); if (configurationXml != null) { // xml parsing below, inserts into Surveys and SurveyPrompts if (populateSurveysFromCampaignXML(db, campaignUrn, configurationXml)) { // i think we're done now; finish up the transaction db.setTransactionSuccessful(); } // else we fail and the transaction gets rolled back } else { db.setTransactionSuccessful(); } } finally { db.endTransaction(); } return rowId; }
From source file:com.openerp.orm.ORM.java
/** * Creates the.//from w ww .ja v a 2s . c om * * @param dbHelper * the db helper * @param values * the values * @return the int */ public int create(BaseDBHelper dbHelper, ContentValues data_values) { int newId = 0; ContentValues values = new ContentValues(); if (data_values.containsKey("id")) { newId = data_values.getAsInteger("id"); } else { newId = createRecordOnserver(dbHelper, data_values); data_values.put("id", newId); } for (Fields field : dbHelper.getColumns()) { values.put(field.getName(), data_values.getAsString(field.getName())); } values.put("oea_name", OpenERPAccountManager.currentUser(context).getAndroidName()); // 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); createM2MRecords(values.getAsString("id"), m2mArray, key, dbHelper, m2m, values); } catch (Exception e) { } values.remove(key); } // Handling Many2One Record HashMap<String, Object> many2onecols = dbHelper.getMany2OneColumns(); for (String key : many2onecols.keySet()) { try { if (!values.getAsString(key).equals("false")) { JSONArray m2oArray = new JSONArray(values.getAsString(key)); values.put(key, many2oneRecord(m2oArray)); List<Integer> list = new ArrayList<Integer>(); int m2o_id = Integer.parseInt(many2oneRecord(m2oArray)); list.add(m2o_id); BaseDBHelper m2oDb = ((Many2One) many2onecols.get(key)).getM2OObject(); if (!m2oDb.hasRecord(m2oDb, m2o_id)) { oe_obj.syncReferenceTables(m2oDb, list, false); } } } catch (Exception e) { } } SQLiteDatabase db = getWritableDatabase(); db.insert(modelToTable(dbHelper.getModelName()), null, values); db.close(); return newId; }
From source file:com.openerp.orm.ORM.java
/** * Creates the many2many records for a column. * //from w w w .ja v a2 s.c o m * @param id * the id * @param values * the values * @param key * the key * @param dbHelper * the db helper * @param m2m * the m2m * @param rootRow * the root row */ private void createM2MRecords(String id, JSONArray values, String key, BaseDBHelper dbHelper, Many2Many m2m, ContentValues rootRow) { String table1 = modelToTable(dbHelper.getModelName()); String table2 = ""; BaseDBHelper tbl2Obj = null; if (m2m.isM2MObject()) { tbl2Obj = (BaseDBHelper) m2m.getM2mObject(); table2 = modelToTable(tbl2Obj.getModelName()); } else { table2 = modelToTable(m2m.getModel_name()); } String rel_table = table1 + "_" + table2 + "_rel"; String col1 = table1 + "_id"; String col2 = table2 + "_id"; String col3 = "oea_name"; // Temp dummy helper BaseDBHelper newDb = generateM2MHelper(dbHelper, m2m); int loop_val = (values.length() > 10) ? 10 : values.length(); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < loop_val; i++) { try { int row_id = 0; if (values.get(i) instanceof JSONArray) { row_id = values.getJSONArray(i).getInt(0); } if (values.get(i) instanceof JSONObject) { JSONObject obj = (JSONObject) values.get(i); if (obj.has("id")) { row_id = obj.getInt("id"); } } if (values.get(i) instanceof Integer) { row_id = values.getInt(i); } ContentValues m2mvals = new ContentValues(); String android_name = OpenERPAccountManager.currentUser(context).getAndroidName(); m2mvals.put(col1, id); m2mvals.put(col2, row_id); m2mvals.put(col3, android_name); int res = Integer.parseInt( search(newDb, new String[] { col1 + " = ?", "AND", col2 + "= ?", "AND", col3 + " = ?" }, new String[] { id, row_id + "", android_name }).get("total").toString()); if (res == 0) { SQLiteDatabase db = getWritableDatabase(); db.insert(rel_table, null, m2mvals); db.close(); } if (tbl2Obj != null && !tbl2Obj.hasRecord(tbl2Obj, row_id)) { list.add(row_id); } } catch (Exception e) { e.printStackTrace(); } } if (list.size() > 0) { oe_obj.syncReferenceTables(tbl2Obj, list, false); } }
From source file:at.bitfire.davdroid.AccountSettings.java
@SuppressWarnings({ "Recycle", "unused" }) private void update_2_3() { // Don't show a warning for Android updates anymore accountManager.setUserData(account, "last_android_version", null); Long serviceCardDAV = null, serviceCalDAV = null; ServiceDB.OpenHelper dbHelper = new ServiceDB.OpenHelper(context); try {/*w w w.j a va 2 s . c o m*/ SQLiteDatabase db = dbHelper.getWritableDatabase(); // we have to create the WebDAV Service database only from the old address book, calendar and task list URLs // CardDAV: migrate address books ContentProviderClient client = context.getContentResolver() .acquireContentProviderClient(ContactsContract.AUTHORITY); if (client != null) try { LocalAddressBook addrBook = new LocalAddressBook(account, client); String url = addrBook.getURL(); if (url != null) { App.log.fine("Migrating address book " + url); // insert CardDAV service ContentValues values = new ContentValues(); values.put(Services.ACCOUNT_NAME, account.name); values.put(Services.SERVICE, Services.SERVICE_CARDDAV); serviceCardDAV = db.insert(Services._TABLE, null, values); // insert address book values.clear(); values.put(Collections.SERVICE_ID, serviceCardDAV); values.put(Collections.URL, url); values.put(Collections.SYNC, 1); db.insert(Collections._TABLE, null, values); // insert home set HttpUrl homeSet = HttpUrl.parse(url).resolve("../"); values.clear(); values.put(HomeSets.SERVICE_ID, serviceCardDAV); values.put(HomeSets.URL, homeSet.toString()); db.insert(HomeSets._TABLE, null, values); } } catch (ContactsStorageException e) { App.log.log(Level.SEVERE, "Couldn't migrate address book", e); } finally { client.release(); } // CalDAV: migrate calendars + task lists Set<String> collections = new HashSet<>(); Set<HttpUrl> homeSets = new HashSet<>(); client = context.getContentResolver().acquireContentProviderClient(CalendarContract.AUTHORITY); if (client != null) try { LocalCalendar calendars[] = (LocalCalendar[]) LocalCalendar.find(account, client, LocalCalendar.Factory.INSTANCE, null, null); for (LocalCalendar calendar : calendars) { String url = calendar.getName(); App.log.fine("Migrating calendar " + url); collections.add(url); homeSets.add(HttpUrl.parse(url).resolve("../")); } } catch (CalendarStorageException e) { App.log.log(Level.SEVERE, "Couldn't migrate calendars", e); } finally { client.release(); } TaskProvider provider = LocalTaskList.acquireTaskProvider(context.getContentResolver()); if (provider != null) try { LocalTaskList[] taskLists = (LocalTaskList[]) LocalTaskList.find(account, provider, LocalTaskList.Factory.INSTANCE, null, null); for (LocalTaskList taskList : taskLists) { String url = taskList.getSyncId(); App.log.fine("Migrating task list " + url); collections.add(url); homeSets.add(HttpUrl.parse(url).resolve("../")); } } catch (CalendarStorageException e) { App.log.log(Level.SEVERE, "Couldn't migrate task lists", e); } finally { provider.close(); } if (!collections.isEmpty()) { // insert CalDAV service ContentValues values = new ContentValues(); values.put(Services.ACCOUNT_NAME, account.name); values.put(Services.SERVICE, Services.SERVICE_CALDAV); serviceCalDAV = db.insert(Services._TABLE, null, values); // insert collections for (String url : collections) { values.clear(); values.put(Collections.SERVICE_ID, serviceCalDAV); values.put(Collections.URL, url); values.put(Collections.SYNC, 1); db.insert(Collections._TABLE, null, values); } // insert home sets for (HttpUrl homeSet : homeSets) { values.clear(); values.put(HomeSets.SERVICE_ID, serviceCalDAV); values.put(HomeSets.URL, homeSet.toString()); db.insert(HomeSets._TABLE, null, values); } } } finally { dbHelper.close(); } // initiate service detection (refresh) to get display names, colors etc. Intent refresh = new Intent(context, DavService.class); refresh.setAction(DavService.ACTION_REFRESH_COLLECTIONS); if (serviceCardDAV != null) { refresh.putExtra(DavService.EXTRA_DAV_SERVICE_ID, serviceCardDAV); context.startService(refresh); } if (serviceCalDAV != null) { refresh.putExtra(DavService.EXTRA_DAV_SERVICE_ID, serviceCalDAV); context.startService(refresh); } }
From source file:com.openerp.orm.ORM.java
/** * Update m2 m records.//w w w .j ava 2s .c o m * * @param id * the id * @param values * the values * @param key * the key * @param dbHelper * the db helper * @param m2m * the m2m * @param rootRow * the root row */ private void updateM2MRecords(String id, JSONArray values, String key, BaseDBHelper dbHelper, Many2Many m2m, ContentValues rootRow) { // TODO Auto-generated method stub String table1 = modelToTable(dbHelper.getModelName()); String table2 = ""; BaseDBHelper tbl2Obj = null; if (m2m.isM2MObject()) { tbl2Obj = (BaseDBHelper) m2m.getM2mObject(); table2 = modelToTable(tbl2Obj.getModelName()); } else { table2 = modelToTable(m2m.getModel_name()); } String rel_table = table1 + "_" + table2 + "_rel"; String col1 = table1 + "_id"; String col2 = table2 + "_id"; String col3 = "oea_name"; // Temp dummy helper BaseDBHelper newDb = generateM2MHelper(dbHelper, m2m); for (int i = 0; i < values.length(); i++) { try { int row_id = 0; if (values.get(i) instanceof JSONArray) { row_id = values.getJSONArray(i).getInt(0); } if (values.get(i) instanceof JSONObject) { JSONObject obj = (JSONObject) values.get(i); if (obj.has("id")) { row_id = obj.getInt("id"); } } if (values.get(i) instanceof Integer) { row_id = values.getInt(i); } ContentValues m2mvals = new ContentValues(); m2mvals.put(col1, id); m2mvals.put(col2, row_id); m2mvals.put(col3, user_name); int res = (Integer) this .search(newDb, new String[] { col1 + " = ?", "AND", col2 + "= ?", "AND", col3 + " = ?" }, new String[] { id, row_id + "", user_name }) .get("total"); SQLiteDatabase db = getWritableDatabase(); if (res == 0) { db.insert(rel_table, null, m2mvals); if (tbl2Obj != null) { List<Integer> list = new ArrayList<Integer>(); list.add(row_id); oe_obj.syncReferenceTables(tbl2Obj, list, false); } } else { db.update(rel_table, m2mvals, col1 + " = " + id + " AND " + col2 + " = " + row_id + " AND " + col3 + " = '" + user_name + "' ", null); } db.close(); } catch (Exception e) { e.printStackTrace(); } } }