List of usage examples for android.content ContentValues getAsString
public String getAsString(String key)
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
long addObjectByJson(long contactId, JSONObject json, long hash, byte[] raw, Integer intKey) { try {/*from www . ja va 2 s. co m*/ long objId = getNextId(); long seqId = json.optLong(DbObjects.SEQUENCE_ID); long timestamp = json.getLong(DbObjects.TIMESTAMP); String feedName = json.getString(DbObjects.FEED_NAME); String type = json.getString(DbObjects.TYPE); String appId = json.getString(DbObjects.APP_ID); ContentValues cv = new ContentValues(); cv.put(DbObject._ID, objId); cv.put(DbObject.APP_ID, appId); cv.put(DbObject.FEED_NAME, feedName); cv.put(DbObject.CONTACT_ID, contactId); cv.put(DbObject.TYPE, type); cv.put(DbObject.SEQUENCE_ID, seqId); cv.put(DbObject.JSON, json.toString()); cv.put(DbObject.TIMESTAMP, timestamp); cv.put(DbObject.HASH, hash); cv.put(DbObject.SENT, 1); cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime()); if (raw != null) { cv.put(DbObject.RAW, raw); } if (intKey != null) { cv.put(DbObject.KEY_INT, intKey); } // TODO: Deprecated!! if (json.has(DbObject.CHILD_FEED_NAME)) { cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME)); } if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT) throw new RuntimeException("Messasge size is too large for sending"); long newObjId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv); String notifyName = feedName; if (json.has(DbObjects.TARGET_HASH)) { long hashA = json.optLong(DbObjects.TARGET_HASH); long idA = objIdForHash(hashA); notifyName = feedName + ":" + hashA; String relation; if (json.has(DbObjects.TARGET_RELATION)) { relation = json.optString(DbObjects.TARGET_RELATION); } else { relation = DbRelation.RELATION_PARENT; } if (idA == -1) { Log.e(TAG, "No objId found for hash " + hashA); } else { addObjRelation(idA, newObjId, relation); } } ContentResolver resolver = mContext.getContentResolver(); DungBeetleContentProvider.notifyDependencies(this, resolver, notifyName); updateObjModification(App.instance().getMusubi().objForId(newObjId)); return objId; } catch (Exception e) { if (DBG) Log.e(TAG, "Error adding object by json.", e); return -1; } }
From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() != 3) { throw new SQLException("Unknown URI (does not specify instance!) " + uri); }/* ww w .j a va 2s.co m*/ String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = segments.get(2); SQLiteDatabase db = null; int count = 0; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); boolean success = false; try { success = ODKDatabaseUtils.get().hasTableId(db, tableId); } catch (Exception e) { e.printStackTrace(); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } String dbTableName = "\"" + tableId + "\""; // run the query to get all the ids... List<IdStruct> idStructs = new ArrayList<IdStruct>(); Cursor ref = null; try { // use this provider's query interface to get the set of ids that // match (if any) ref = this.query(uri, null, where, whereArgs, null); if (ref.getCount() != 0) { ref.moveToFirst(); do { String iId = ODKDatabaseUtils.get().getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(ref, ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); } while (ref.moveToNext()); } } finally { if (ref != null) { ref.close(); } } // update the values string... if (values.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) { Date xmlPublishDate = new Date(); values.put(InstanceColumns.XML_PUBLISH_TIMESTAMP, TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime())); String xmlPublishStatus = values.getAsString(InstanceColumns.XML_PUBLISH_STATUS); if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) { String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate); values.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } db.beginTransaction(); String[] args = new String[1]; for (IdStruct idStruct : idStructs) { args[0] = idStruct.idUploadsTable; count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args); } db.setTransactionSuccessful(); } finally { if (db != null) { db.endTransaction(); db.close(); } } getContext().getContentResolver().notifyChange(uri, null); return count; }
From source file:com.haibison.android.anhuu.FragmentFiles.java
/** * Updates or inserts {@code path} into history database. *///w ww. ja v a2 s .c o m private void updateDbHistory(Uri path) { if (BuildConfig.DEBUG) Log.d(CLASSNAME, "updateDbHistory() >> path = " + path); Calendar cal = Calendar.getInstance(); final long beginTodayMillis = cal.getTimeInMillis() - (cal.get(Calendar.HOUR_OF_DAY) * 60 * 60 * 1000 + cal.get(Calendar.MINUTE) * 60 * 1000 + cal.get(Calendar.SECOND) * 1000); if (BuildConfig.DEBUG) { Log.d(CLASSNAME, String.format("beginToday = %s (%s)", DbUtils.formatNumber(beginTodayMillis), new Date(beginTodayMillis))); Log.d(CLASSNAME, String.format("endToday = %s (%s)", DbUtils.formatNumber(beginTodayMillis + DateUtils.DAY_IN_MILLIS), new Date(beginTodayMillis + DateUtils.DAY_IN_MILLIS))); } /* * Does the update and returns the number of rows updated. */ long time = new Date().getTime(); ContentValues values = new ContentValues(); values.put(HistoryContract.COLUMN_PROVIDER_ID, BaseFileProviderUtils.getProviderId(path.getAuthority())); values.put(HistoryContract.COLUMN_FILE_TYPE, BaseFile.FILE_TYPE_DIRECTORY); values.put(HistoryContract.COLUMN_URI, path.toString()); values.put(HistoryContract.COLUMN_MODIFICATION_TIME, DbUtils.formatNumber(time)); int count = getActivity().getContentResolver().update(HistoryContract.genContentUri(getActivity()), values, String.format("%s >= '%s' and %s < '%s' and %s = %s and %s like %s", HistoryContract.COLUMN_MODIFICATION_TIME, DbUtils.formatNumber(beginTodayMillis), HistoryContract.COLUMN_MODIFICATION_TIME, DbUtils.formatNumber(beginTodayMillis + DateUtils.DAY_IN_MILLIS), HistoryContract.COLUMN_PROVIDER_ID, DatabaseUtils.sqlEscapeString(values.getAsString(HistoryContract.COLUMN_PROVIDER_ID)), HistoryContract.COLUMN_URI, DatabaseUtils.sqlEscapeString(values.getAsString(HistoryContract.COLUMN_URI))), null); if (count <= 0) { values.put(HistoryContract.COLUMN_CREATE_TIME, DbUtils.formatNumber(time)); getActivity().getContentResolver().insert(HistoryContract.genContentUri(getActivity()), values); } }
From source file:com.akop.bach.parser.XboxLiveParser.java
private void parseAccountSummary(XboxLiveAccount account) throws ParserException, IOException { ContentValues cv = parseSummaryData(account); ContentResolver cr = mContext.getContentResolver(); long accountId = account.getId(); boolean newRecord = true; long started = System.currentTimeMillis(); Cursor c = cr.query(Profiles.CONTENT_URI, new String[] { Profiles._ID }, Profiles.ACCOUNT_ID + "=" + accountId, null, null); if (c != null) { if (c.moveToFirst()) newRecord = false;/* w w w.ja v a 2 s .c om*/ c.close(); } if (newRecord) { cv.put(Profiles.ACCOUNT_ID, account.getId()); cv.put(Profiles.UUID, account.getUuid()); cr.insert(Profiles.CONTENT_URI, cv); } else { cr.update(Profiles.CONTENT_URI, cv, Profiles.ACCOUNT_ID + "=" + accountId, null); } cr.notifyChange(Profiles.CONTENT_URI, null); if (App.getConfig().logToConsole()) displayTimeTaken("Summary update", started); account.refresh(Preferences.get(mContext)); account.setGamertag(cv.getAsString(Profiles.GAMERTAG)); account.setIconUrl(cv.getAsString(Profiles.ICON_URL)); account.setGoldStatus(cv.getAsBoolean(Profiles.IS_GOLD)); account.setLastSummaryUpdate(System.currentTimeMillis()); account.save(Preferences.get(mContext)); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId, ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) { String rowId = null;//from w w w.j a v a2s . c o m String whereClause = null; boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE); boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null); String[] whereArgs = new String[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1]; boolean update = false; if (cvValues.size() <= 0) { throw new IllegalArgumentException(t + ": No values to add into table " + tableId); } ContentValues cvDataTableVal = new ContentValues(); cvDataTableVal.putAll(cvValues); if (cvDataTableVal.containsKey(DataTableColumns.ID)) { // The user specified a row id; we need to determine whether to // insert or update the record, or to reject the action because // there are either checkpoint records for this row id, or, if // a server conflict is associated with this row, that the // _conflict_type to update was not specified. // // i.e., the tuple (_id, _conflict_type) should be unique. If // we find that there are more than 0 or 1 records matching this // tuple, then we should reject the update request. // // TODO: perhaps we want to allow updates to the local conflict // row if there are no checkpoints on it? I.e., change the // tri-state conflict type to a pair of states (local / remote). // and all local changes are flagged local. Remote only exists // if the server is in conflict. rowId = cvDataTableVal.getAsString(DataTableColumns.ID); if (rowId == null) { throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null"); } if (specifiesConflictType) { if (nullConflictType) { whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " IS NULL"; whereArgs[0] = rowId; } else { whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " = ?"; whereArgs[0] = rowId; whereArgs[1] = cvValues.getAsString(DataTableColumns.CONFLICT_TYPE); } } else { whereClause = DataTableColumns.ID + " = ?"; whereArgs[0] = rowId; } String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause; String[] selArgs = whereArgs; Cursor cursor = rawQuery(db, sel, selArgs); // There must be only one row in the db for the update to work if (shouldUpdate) { if (cursor.getCount() == 1) { update = true; } else if (cursor.getCount() > 1) { throw new IllegalArgumentException( t + ": row id " + rowId + " has more than 1 row in table " + tableId); } } else { if (cursor.getCount() > 0) { throw new IllegalArgumentException( t + ": id " + rowId + " is already present in table " + tableId); } } } else { rowId = "uuid:" + UUID.randomUUID().toString(); } // TODO: This is broken w.r.t. updates of partial fields // TODO: This is broken w.r.t. updates of partial fields // TODO: This is broken w.r.t. updates of partial fields // TODO: This is broken w.r.t. updates of partial fields if (!cvDataTableVal.containsKey(DataTableColumns.ID)) { cvDataTableVal.put(DataTableColumns.ID, rowId); } if (update) { if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE) || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) { cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.changed.name()); } if (cvDataTableVal.containsKey(DataTableColumns.LOCALE) && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) { cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE); } if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE) && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) { cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete()); } if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP) || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) { String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()); cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp); } if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR) || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) { cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR); } } else { if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG) || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) { cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG); } if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE) || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) { cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name()); } if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) { cvDataTableVal.putNull(DataTableColumns.CONFLICT_TYPE); } if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_TYPE) || (cvDataTableVal.get(DataTableColumns.FILTER_TYPE) == null)) { cvDataTableVal.put(DataTableColumns.FILTER_TYPE, DataTableColumns.DEFAULT_FILTER_TYPE); } if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_VALUE) || (cvDataTableVal.get(DataTableColumns.FILTER_VALUE) == null)) { cvDataTableVal.put(DataTableColumns.FILTER_VALUE, DataTableColumns.DEFAULT_FILTER_VALUE); } if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) { cvDataTableVal.putNull(DataTableColumns.FORM_ID); } if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE) || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) { cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE); } if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE) || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) { cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete()); } if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP) || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) { String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()); cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp); } if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR) || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) { cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR); } } cleanUpValuesMap(orderedColumns, cvDataTableVal); boolean dbWithinTransaction = db.inTransaction(); try { if (!dbWithinTransaction) { db.beginTransaction(); } if (update) { db.update(tableId, cvDataTableVal, whereClause, whereArgs); } else { db.insertOrThrow(tableId, null, cvDataTableVal); } if (!dbWithinTransaction) { db.setTransactionSuccessful(); } } finally { if (!dbWithinTransaction) { db.endTransaction(); } } }
From source file:org.opendatakit.sensors.manager.WorkerThread.java
private void parseSensorDataAndInsertIntoTable(ODKSensor aSensor, String strTableDef, Bundle dataBundle) { JSONObject jsonTableDef = null;//from w ww . ja v a 2s. c o m ContentValues tablesValues = new ContentValues(); SQLiteDatabase db = null; try { db = DatabaseFactory.get().getDatabase(serviceContext, aSensor.getAppNameForDatabase()); jsonTableDef = new JSONObject(strTableDef); String tableId = jsonTableDef.getJSONObject(ODKJsonNames.jsonTableStr) .getString(ODKJsonNames.jsonTableIdStr); if (tableId == null) { return; } boolean success; success = false; try { success = ODKDatabaseUtils.get().hasTableId(db, tableId); } catch (Exception e) { e.printStackTrace(); throw new SQLException("Exception testing for tableId " + tableId); } if (!success) { sensorManager.parseDriverTableDefintionAndCreateTable(aSensor.getSensorID(), aSensor.getAppNameForDatabase(), db); } success = false; try { success = ODKDatabaseUtils.get().hasTableId(db, tableId); } catch (Exception e) { e.printStackTrace(); throw new SQLException("Exception testing for tableId " + tableId); } if (!success) { throw new SQLException("Unable to create tableId " + tableId); } ArrayList<ColumnDefinition> orderedDefs = TableUtil.get().getColumnDefinitions(db, aSensor.getAppNameForDatabase(), tableId); // Create the columns for the driver table for (ColumnDefinition col : orderedDefs) { if (!col.isUnitOfRetention()) { continue; } String colName = col.getElementKey(); ElementType type = col.getType(); if (colName.equals(DataSeries.SENSOR_ID)) { // special treatment tablesValues.put(colName, aSensor.getSensorID()); } else if (type.getDataType() == ElementDataType.bool) { Boolean boolColData = dataBundle.containsKey(colName) ? dataBundle.getBoolean(colName) : null; Integer colData = (boolColData == null) ? null : (boolColData ? 1 : 0); tablesValues.put(colName, colData); } else if (type.getDataType() == ElementDataType.integer) { Integer colData = dataBundle.containsKey(colName) ? dataBundle.getInt(colName) : null; tablesValues.put(colName, colData); } else if (type.getDataType() == ElementDataType.number) { Double colData = dataBundle.containsKey(colName) ? dataBundle.getDouble(colName) : null; tablesValues.put(colName, colData); } else { // everything else is a string value coming across the wire... String colData = dataBundle.containsKey(colName) ? dataBundle.getString(colName) : null; tablesValues.put(colName, colData); } } if (tablesValues.size() > 0) { Log.i(TAG, "Writing db values for sensor:" + aSensor.getSensorID()); String rowId = tablesValues.containsKey(DataTableColumns.ID) ? tablesValues.getAsString(DataTableColumns.ID) : null; if (rowId == null) { rowId = ODKDataUtils.genUUID(); } ODKDatabaseUtils.get().insertDataIntoExistingDBTableWithId(db, tableId, orderedDefs, tablesValues, rowId); } } catch (Exception e) { e.printStackTrace(); } finally { if (db != null) { db.close(); } } }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues cv, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); if (segments.size() != 3) { throw new SQLException("Unknown URI (does not specify instance!) " + uri); }/*from w w w . j av a 2 s . c om*/ String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = segments.get(2); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; int count = 0; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName, dbHandleName); db.beginTransactionNonExclusive(); boolean success = false; try { success = ODKDatabaseImplUtils.get().hasTableId(db, tableId); } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } internalUpdate(db, uri, appName, tableId); // run the query to get all the ids... List<IdStruct> idStructs = new ArrayList<IdStruct>(); Cursor ref = null; try { // use this provider's query interface to get the set of ids that // match (if any) ref = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null); ref.moveToFirst(); if (ref.getCount() != 0) { do { String iId = CursorUtils.getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = CursorUtils.getIndexAsString(ref, ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); } while (ref.moveToNext()); } } finally { if (ref != null) { ref.close(); } } // update the values string... if (cv.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) { Date xmlPublishDate = new Date(); cv.put(InstanceColumns.XML_PUBLISH_TIMESTAMP, TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime())); String xmlPublishStatus = cv.getAsString(InstanceColumns.XML_PUBLISH_STATUS); if (!cv.containsKey(InstanceColumns.DISPLAY_SUBTEXT)) { String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate); cv.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } Map<String, Object> values = new HashMap<String, Object>(); for (String key : cv.keySet()) { values.put(key, cv.get(key)); } Object[] args = new String[1]; for (IdStruct idStruct : idStructs) { args[0] = idStruct.idUploadsTable; count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args); } db.setTransactionSuccessful(); } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName, dbHandleName); } } } } getContext().getContentResolver().notifyChange(uri, null); return count; }
From source file:it.gmariotti.android.examples.googleaccount.SmsRestoreGDriveActivity.java
/** * Backup SMSs to GDrive// w w w . ja va 2 s . c o m */ private void restoreSmsFromGDrive() { // Check for use data folder CheckBox checkbox = (CheckBox) findViewById(R.id.appdatafolder); if (checkbox != null && checkbox.isChecked()) useDataFolder = true; else useDataFolder = false; Thread t = new Thread(new Runnable() { @Override public void run() { try { showToast("Start process"); Map<String, Map<String, String>> messages = new HashMap<String, Map<String, String>>(); // Create sms backup Folder File folder = null; if (mService == null) initService(); String folderId = "appdata"; if (!useDataFolder) { folder = _isFolderExists(); if (folder != null) folderId = folder.getId(); } if (folderId != null) { Files.List request = mService.files().list() .setQ("mimeType = '" + MIME_TEXT_PLAIN + "' and '" + folderId + "' in parents "); FileList files = request.execute(); if (files != null) { for (File file : files.getItems()) { // TODO: get only a file // Meta data Log.i(TAG, "Title: " + file.getTitle()); Log.i(TAG, "Description: " + file.getDescription()); Log.i(TAG, "MIME type: " + file.getMimeType()); String content = getContentFile(file); if (content != null) { // Parse Json JSONObject json = new JSONObject(content); JSONArray msgs = (JSONArray) json.get("messages"); for (int i = 0; i < msgs.length(); i++) { JSONObject json_dataSms = msgs.getJSONObject(i); Iterator<String> keys = json_dataSms.keys(); Map<String, String> message = new HashMap<String, String>(); String idKey = null; while (keys.hasNext()) { String key = (String) keys.next(); message.put(key, json_dataSms.getString(key)); idKey = json_dataSms.getString(TelephonyProviderConstants.Sms._ID); } // Put message in hashMap messages.put(idKey, message); } restore(messages); continue; } } } } } catch (UserRecoverableAuthIOException e) { Intent intent = e.getIntent(); startActivityForResult(intent, REQUEST_AUTHORIZATION_FOLDER); } catch (IOException e) { Log.e("TAG", "Error in backup", e); } catch (JSONException e) { Log.e("TAG", "Error in backup", e); } } private void restore(Map<String, Map<String, String>> messages) { if (messages != null) { for (Map.Entry<String, Map<String, String>> entry : messages.entrySet()) { String idkey = entry.getKey(); Map<String, String> msg = entry.getValue(); String type = msg.get(TelephonyProviderConstants.Sms.TYPE); ContentValues values = new ContentValues(); values.put(TelephonyProviderConstants.Sms.BODY, msg.get(TelephonyProviderConstants.Sms.BODY)); values.put(TelephonyProviderConstants.Sms.ADDRESS, msg.get(TelephonyProviderConstants.Sms.ADDRESS)); values.put(TelephonyProviderConstants.Sms.TYPE, msg.get(TelephonyProviderConstants.Sms.TYPE)); values.put(TelephonyProviderConstants.Sms.PROTOCOL, msg.get(TelephonyProviderConstants.Sms.PROTOCOL)); values.put(TelephonyProviderConstants.Sms.SERVICE_CENTER, msg.get(TelephonyProviderConstants.Sms.SERVICE_CENTER)); values.put(TelephonyProviderConstants.Sms.DATE, msg.get(TelephonyProviderConstants.Sms.DATE)); values.put(TelephonyProviderConstants.Sms.STATUS, msg.get(TelephonyProviderConstants.Sms.STATUS)); // values.put(TelephonyProviderConstants.Sms.THREAD_ID, // msg.get(TelephonyProviderConstants.Sms.THREAD_ID)); values.put(TelephonyProviderConstants.Sms.READ, msg.get(TelephonyProviderConstants.Sms.READ)); values.put(TelephonyProviderConstants.Sms.DATE_SENT, msg.get(TelephonyProviderConstants.Sms.DATE_SENT)); /* * for (Map.Entry<String, String> fields : * msg.entrySet()) { String idfield = fields.getKey(); * String valueField = fields.getValue(); * * values.put(idfield,valueField); } */ if (type != null && (Integer.parseInt(type) == TelephonyProviderConstants.Sms.MESSAGE_TYPE_INBOX || Integer .parseInt(type) == TelephonyProviderConstants.Sms.MESSAGE_TYPE_SENT) && !smsExists(values)) { final Uri uri = getContentResolver().insert(TelephonyProviderConstants.Sms.CONTENT_URI, values); if (uri != null) { showToast("Restored message=" + msg.get(TelephonyProviderConstants.Sms.BODY)); } } else { Log.d(TAG, "ignore"); } } } } private boolean smsExists(ContentValues values) { // just assume equality on date+address+type Cursor c = getContentResolver().query(TelephonyProviderConstants.Sms.CONTENT_URI, new String[] { "_id" }, "date = ? AND address = ? AND type = ?", new String[] { values.getAsString(TelephonyProviderConstants.Sms.DATE), values.getAsString(TelephonyProviderConstants.Sms.ADDRESS), values.getAsString(TelephonyProviderConstants.Sms.TYPE) }, null); boolean exists = false; if (c != null) { exists = c.getCount() > 0; c.close(); } return exists; } }); t.start(); }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * If the caller specified a complex json value for a structured type, flush * the value through to the individual columns. * //from w ww.j a v a2 s . co m * @param orderedColumns * @param values */ private void cleanUpValuesMap(ArrayList<ColumnDefinition> orderedColumns, ContentValues values) { Map<String, String> toBeResolved = new HashMap<String, String>(); for (String key : values.keySet()) { if (DataTableColumns.CONFLICT_TYPE.equals(key)) { continue; } else if (DataTableColumns.FILTER_TYPE.equals(key)) { continue; } else if (DataTableColumns.FILTER_TYPE.equals(key)) { continue; } else if (DataTableColumns.FILTER_VALUE.equals(key)) { continue; } else if (DataTableColumns.FORM_ID.equals(key)) { continue; } else if (DataTableColumns.ID.equals(key)) { continue; } else if (DataTableColumns.LOCALE.equals(key)) { continue; } else if (DataTableColumns.ROW_ETAG.equals(key)) { continue; } else if (DataTableColumns.SAVEPOINT_CREATOR.equals(key)) { continue; } else if (DataTableColumns.SAVEPOINT_TIMESTAMP.equals(key)) { continue; } else if (DataTableColumns.SAVEPOINT_TYPE.equals(key)) { continue; } else if (DataTableColumns.SYNC_STATE.equals(key)) { continue; } else if (DataTableColumns._ID.equals(key)) { continue; } // OK it is one of the data columns ColumnDefinition cp = ColumnDefinition.find(orderedColumns, key); if (!cp.isUnitOfRetention()) { toBeResolved.put(key, values.getAsString(key)); } } // remove these non-retained values from the values set... for (String key : toBeResolved.keySet()) { values.remove(key); } while (!toBeResolved.isEmpty()) { Map<String, String> moreToResolve = new HashMap<String, String>(); for (Map.Entry<String, String> entry : toBeResolved.entrySet()) { String key = entry.getKey(); String json = entry.getValue(); if (json == null) { // don't need to do anything // since the value is null continue; } ColumnDefinition cp = ColumnDefinition.find(orderedColumns, key); try { Map<String, Object> struct = ODKFileUtils.mapper.readValue(json, Map.class); for (ColumnDefinition child : cp.getChildren()) { String subkey = child.getElementKey(); ColumnDefinition subcp = ColumnDefinition.find(orderedColumns, subkey); if (subcp.isUnitOfRetention()) { ElementType subtype = subcp.getType(); ElementDataType type = subtype.getDataType(); if (type == ElementDataType.integer) { values.put(subkey, (Integer) struct.get(subcp.getElementName())); } else if (type == ElementDataType.number) { values.put(subkey, (Double) struct.get(subcp.getElementName())); } else if (type == ElementDataType.bool) { values.put(subkey, ((Boolean) struct.get(subcp.getElementName())) ? 1 : 0); } else { values.put(subkey, (String) struct.get(subcp.getElementName())); } } else { // this must be a javascript structure... re-JSON it and save (for // next round). moreToResolve.put(subkey, ODKFileUtils.mapper.writeValueAsString(struct.get(subcp.getElementName()))); } } } catch (JsonParseException e) { e.printStackTrace(); throw new IllegalStateException("should not be happening"); } catch (JsonMappingException e) { e.printStackTrace(); throw new IllegalStateException("should not be happening"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("should not be happening"); } } toBeResolved = moreToResolve; } }
From source file:ca.zadrox.dota2esportticker.service.UpdateTeamsService.java
private void updateSearchedTeams(String searchName) { LOGD(TAG, "starting search update"); // actually, first, check for connectivity: if (!checkForConnectivity()) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_NO_CONNECTIVITY)); LOGD(TAG, "returning due to no connectivity"); return;/* w w w . j a va2 s. co m*/ } LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING)); final String BASE_URL = "http://www.gosugamers.net/dota2/rankings" + "?tname=" + searchName.replace(' ', '+') + "&tunranked=0#team"; final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/"; try { String rawHtml = new OkHttpClient().newCall(new Request.Builder().url(BASE_URL).build()).execute() .body().string(); String processedHtml = rawHtml.substring(rawHtml.indexOf("<div id=\"col1\" class=\"rows\">"), rawHtml.indexOf("<div id=\"col2\" class=\"rows\">")); Elements teamRows = Jsoup.parse(processedHtml).getElementsByClass("ranking-link"); ExecutorService executorService = Executors.newFixedThreadPool(10); HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>(); HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>(); for (Element teamRow : teamRows) { ContentValues contentValues = new ContentValues(); String teamId = teamRow.attr("data-id"); contentValues.put(MatchContract.TeamEntry._ID, teamId); String untrimmedTeamName = teamRow.getElementsByTag("h4").first().text(); String teamUrl = TEAM_LINK_BASE_URL + teamId + "-" + untrimmedTeamName.replaceAll("[\\W]?[\\W][\\W]*", "-").toLowerCase(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_URL, teamUrl); String teamName = untrimmedTeamName.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", ""); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_NAME, teamName); if (teamUrl.charAt(teamUrl.length() - 1) == '-') { teamUrl = teamUrl.substring(0, teamUrl.length() - 2); } // then, we query db for id of the team ( Cursor cursor = getContentResolver().query( MatchContract.TeamEntry.buildTeamUri(Long.parseLong(teamId)), new String[] { MatchContract.TeamEntry.COLUMN_TEAM_NAME, MatchContract.TeamEntry.COLUMN_TEAM_URL }, null, null, null); // -> if present, and data remains unchanged, continue. // -> if present, but data is changed, add to update queue. if (cursor.moveToFirst()) { LOGD(TAG, "Team in DB, determining if values need updating"); if (!cursor.getString(0).contentEquals(teamName) || !cursor.getString(1).contentEquals(teamUrl)) { LOGD(TAG, "Team has updated values, double checking logo & writing to DB"); updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } } // -> if not present, add to update queue. else { LOGD(TAG, "Team not in DB. Grabbing logo & writing to DB"); newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } // LOGD(TAG, "\n" + // "data-id: " + teamId + "\n" + // "team-name: " + teamName + "\n" + // "team-url: " + teamUrl); // cursor.close(); } executorService.shutdown(); executorService.awaitTermination(20, TimeUnit.SECONDS); for (ContentValues contentValues : newTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } for (ContentValues contentValues : updateTeamInfo.keySet()) { try { String teamLogo = newTeamInfo.get(contentValues).get(); contentValues.put(MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, teamLogo); String teamId = contentValues.getAsString(MatchContract.TeamEntry._ID); contentValues.remove(MatchContract.TeamEntry._ID); int updatedRows = getContentResolver().update(MatchContract.TeamEntry.CONTENT_URI, contentValues, MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID + " = ?", new String[] { teamId }); LOGD(TAG, "updatedRows: " + updatedRows); } catch (ExecutionException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } } getContentResolver().bulkInsert(MatchContract.TeamEntry.CONTENT_URI, newTeamInfo.keySet().toArray(new ContentValues[newTeamInfo.size()])); } catch (IOException e) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e.printStackTrace(); } catch (InterruptedException e2) { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_ERROR)); e2.printStackTrace(); } // String[] projection = new String[]{ // MatchContract.TeamEntry.TABLE_NAME + "." + MatchContract.TeamEntry._ID, // MatchContract.TeamEntry.COLUMN_TEAM_NAME, // MatchContract.TeamEntry.COLUMN_TEAM_URL, // MatchContract.TeamEntry.COLUMN_TEAM_LOGO_URL, // MatchContract.TeamEntry.COLUMN_TEAM_STARRED, // }; // // String sortOrder = // MatchContract.TeamEntry.COLUMN_TEAM_NAME + " ASC"; // // Cursor c = getContentResolver().query( // MatchContract.TeamEntry.CONTENT_URI, // projection, // MatchContract.TeamEntry.COLUMN_TEAM_NAME + " LIKE '%" + searchName + "%'", // null, // sortOrder // ); // // LOGD(TAG+"/UST", "Starting Printout: "); // int i = 0; // while (c.moveToNext()) { // String teamPrintOut = // "teamId: " + c.getInt(0) + " teamName: " + c.getString(1) + "\n" + // "teamUrl: " + c.getString(2) + "\n" + // "teamLogoUrl: " + c.getString(3) + "\n" + // "isFavourited: " + (c.getInt(4) == 0 ? "false" : "true"); // LOGD(TAG + "/UST", teamPrintOut); // i++; // } // LOGD(TAG+"/UST", "Stopping Printout. Count: " + i); // // c.close(); // use local broadcast manager to hide loading indicator // and signal that cursorloader for top50 can happen. LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); }