List of usage examples for android.content ContentValues getAsInteger
public Integer getAsInteger(String key)
From source file:org.anhonesteffort.flock.sync.calendar.EventFactory.java
protected static ComponentETagPair<Calendar> getEventComponent(String path, ContentValues eventValues) throws InvalidComponentException { Calendar calendar = new Calendar(); VEvent vEvent = new VEvent(); TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); calendar.getProperties().add(Version.VERSION_2_0); handleAttachPropertiesForCopiedRecurrenceWithExceptions(eventValues, vEvent); String uidText = eventValues.getAsString(CalendarContract.Events._SYNC_ID); if (!StringUtils.isEmpty(uidText)) { Uid eventUid = new Uid(uidText); vEvent.getProperties().add(eventUid); }//www . ja v a2 s . c o m try { String organizerText = eventValues.getAsString(CalendarContract.Events.ORGANIZER); if (StringUtils.isNotEmpty(organizerText)) { URI organizerEmail = new URI("mailto", organizerText, null); Organizer organizer = new Organizer(organizerEmail); vEvent.getProperties().add(organizer); } } catch (URISyntaxException e) { Log.e(TAG, "caught exception while parsing URI from organizerText", e); throw new InvalidComponentException("caught exception while parsing URI from organizerText", false, CalDavConstants.CALDAV_NAMESPACE, path, e); } String summaryText = eventValues.getAsString(CalendarContract.Events.TITLE); if (StringUtils.isNotEmpty(summaryText)) { Summary summary = new Summary(summaryText); vEvent.getProperties().add(summary); } String locationText = eventValues.getAsString(CalendarContract.Events.EVENT_LOCATION); if (StringUtils.isNotEmpty(locationText)) { Location location = new Location(locationText); vEvent.getProperties().add(location); } String descriptionText = eventValues.getAsString(CalendarContract.Events.DESCRIPTION); if (StringUtils.isNotEmpty(descriptionText)) { Description description = new Description(descriptionText); vEvent.getProperties().add(description); } Integer status = eventValues.getAsInteger(CalendarContract.Events.STATUS); Long originalInstanceTime = eventValues.getAsLong(CalendarContract.Events.ORIGINAL_INSTANCE_TIME); if (status != null && status != CalendarContract.Events.STATUS_CANCELED && originalInstanceTime != null && originalInstanceTime > 0) { handleAddPropertiesForEditExceptionToRecurring(path, eventValues, vEvent); } if (status != null && status == CalendarContract.Events.STATUS_CONFIRMED) vEvent.getProperties().add(Status.VEVENT_CONFIRMED); else if (status != null && status == CalendarContract.Events.STATUS_CANCELED) handleAddPropertiesForDeletionExceptionToRecurring(path, eventValues, vEvent); else vEvent.getProperties().add(Status.VEVENT_TENTATIVE); Integer availability = eventValues.getAsInteger(CalendarContract.Events.AVAILABILITY); if (availability != null && availability == CalendarContract.Events.AVAILABILITY_BUSY) vEvent.getProperties().add(Transp.OPAQUE); else vEvent.getProperties().add(Transp.TRANSPARENT); Long dtStartMilliseconds = eventValues.getAsLong(CalendarContract.Events.DTSTART); if (dtStartMilliseconds == null) dtStartMilliseconds = eventValues.getAsLong(CalendarContract.Events.ORIGINAL_INSTANCE_TIME); if (dtStartMilliseconds != null) { DtStart dtStart = new DtStart(new Date(dtStartMilliseconds)); String dtStartTZText = eventValues.getAsString(CalendarContract.Events.EVENT_TIMEZONE); if (dtStartTZText != null) { DateTime startDate = new DateTime(dtStartMilliseconds); TimeZone startTimeZone = registry.getTimeZone(dtStartTZText); startDate.setTimeZone(startTimeZone); dtStart = new DtStart(startDate); } vEvent.getProperties().add(dtStart); } else { Log.e(TAG, "no start date found on event"); throw new InvalidComponentException("no start date found on event", false, CalDavConstants.CALDAV_NAMESPACE, path); } Long dtEndMilliseconds = eventValues.getAsLong(CalendarContract.Events.DTEND); if (dtEndMilliseconds != null && dtEndMilliseconds > 0) { DtEnd dtEnd = new DtEnd(new Date(dtEndMilliseconds)); String dtStartTZText = eventValues.getAsString(CalendarContract.Events.EVENT_TIMEZONE); if (dtStartTZText != null) { DateTime endDate = new DateTime(dtEndMilliseconds); TimeZone endTimeZone = registry.getTimeZone(dtStartTZText); endDate.setTimeZone(endTimeZone); dtEnd = new DtEnd(endDate); } vEvent.getProperties().add(dtEnd); } String durationText = eventValues.getAsString(CalendarContract.Events.DURATION); if (StringUtils.isNotEmpty(durationText)) { Dur dur = new Dur(durationText); Duration duration = new Duration(dur); vEvent.getProperties().add(duration); } try { String rRuleText = eventValues.getAsString(CalendarContract.Events.RRULE); if (StringUtils.isNotEmpty(rRuleText)) { RRule rRule = new RRule(rRuleText); vEvent.getProperties().add(rRule); } String rDateText = eventValues.getAsString(CalendarContract.Events.RDATE); if (StringUtils.isNotEmpty(rDateText)) { RDate rDate = new RDate(); rDate.setValue(rDateText); vEvent.getProperties().add(rDate); } String exRuleText = eventValues.getAsString(CalendarContract.Events.EXRULE); if (StringUtils.isNotEmpty(exRuleText)) { ExRule exRule = new ExRule(); exRule.setValue(exRuleText); vEvent.getProperties().add(exRule); } String exDateText = eventValues.getAsString(CalendarContract.Events.EXDATE); if (StringUtils.isNotEmpty(exDateText)) { ExDate exDate = new ExDate(); exDate.setValue(exDateText); vEvent.getProperties().add(exDate); } } catch (ParseException e) { Log.e(TAG, "caught exception while parsing recurrence rule stuff from event values", e); throw new InvalidComponentException( "caught exception while parsing recurrence rule stuff from event values", false, CalDavConstants.CALDAV_NAMESPACE, path, e); } calendar.getComponents().add(vEvent); Optional<String> eTag = Optional.fromNullable(eventValues.getAsString(CalendarContract.Events.SYNC_DATA1)); return new ComponentETagPair<Calendar>(calendar, eTag); }
From source file:com.akop.bach.parser.PsnEuParser.java
@SuppressLint("DefaultLocale") @Override/*from w w w.j a v a 2 s . c om*/ protected void parseGames(PsnAccount account) throws ParserException, IOException { long started = System.currentTimeMillis(); boolean keepGoing = true; List<ContentValues> cvList = new ArrayList<ContentValues>(); for (int startIndex = 0; keepGoing; startIndex += 16) { String url = String.format(URL_GAMES, startIndex); String page = getResponse(url); keepGoing = parseGamePage(startIndex, page, cvList); } final long accountId = account.getId(); ContentResolver cr = mContext.getContentResolver(); String[] queryParams = new String[1]; Cursor c; long updated = System.currentTimeMillis(); List<ContentValues> newCvs = new ArrayList<ContentValues>(100); // Check to see if we already have a record of this game for (ContentValues cv : cvList) { queryParams[0] = cv.getAsString(Games.UID); c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION, Games.ACCOUNT_ID + "=" + accountId + " AND " + Games.UID + "=?", queryParams, null); try { if (c == null || !c.moveToFirst()) // New game { cv.put(Games.ACCOUNT_ID, accountId); cv.put(Games.TROPHIES_DIRTY, 1); cv.put(Games.LAST_UPDATED, updated); newCvs.add(cv); } else // Existing game { boolean isDirty = false; long gameId = c.getLong(COLUMN_GAME_ID); if (c.getInt(COLUMN_GAME_PROGRESS) != cv.getAsInteger(Games.PROGRESS)) isDirty = true; if (c.getInt(COLUMN_GAME_BRONZE) != cv.getAsInteger(Games.UNLOCKED_BRONZE)) isDirty = true; if (c.getInt(COLUMN_GAME_SILVER) != cv.getAsInteger(Games.UNLOCKED_SILVER)) isDirty = true; if (c.getInt(COLUMN_GAME_GOLD) != cv.getAsInteger(Games.UNLOCKED_GOLD)) isDirty = true; if (c.getInt(COLUMN_GAME_PLATINUM) != cv.getAsInteger(Games.UNLOCKED_PLATINUM)) isDirty = true; if (isDirty) cv.put(Games.TROPHIES_DIRTY, 1); cv.put(Games.LAST_UPDATED, updated); cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null); } } finally { if (c != null) c.close(); } } if (App.getConfig().logToConsole()) started = displayTimeTaken("Game page processing", started); if (newCvs.size() > 0) { ContentValues[] cvs = new ContentValues[newCvs.size()]; newCvs.toArray(cvs); cr.bulkInsert(Games.CONTENT_URI, cvs); if (App.getConfig().logToConsole()) displayTimeTaken("Game page insertion", started); } account.refresh(Preferences.get(mContext)); account.setLastGameUpdate(System.currentTimeMillis()); account.save(Preferences.get(mContext)); cr.notifyChange(Games.CONTENT_URI, null); }
From source file:android.pim.vcard.VCardBuilder.java
public VCardBuilder appendEmails(final List<ContentValues> contentValuesList) { boolean emailAddressExists = false; if (contentValuesList != null) { final Set<String> addressSet = new HashSet<String>(); for (ContentValues contentValues : contentValuesList) { String emailAddress = contentValues.getAsString(Email.DATA); if (emailAddress != null) { emailAddress = emailAddress.trim(); }//from w w w .j a v a 2 s . c om if (TextUtils.isEmpty(emailAddress)) { continue; } Integer typeAsObject = contentValues.getAsInteger(Email.TYPE); final int type = (typeAsObject != null ? typeAsObject : DEFAULT_EMAIL_TYPE); final String label = contentValues.getAsString(Email.LABEL); Integer isPrimaryAsInteger = contentValues.getAsInteger(Email.IS_PRIMARY); final boolean isPrimary = (isPrimaryAsInteger != null ? (isPrimaryAsInteger > 0) : false); emailAddressExists = true; if (!addressSet.contains(emailAddress)) { addressSet.add(emailAddress); appendEmailLine(type, label, emailAddress, isPrimary); } } } if (!emailAddressExists && mIsDoCoMo) { appendEmailLine(Email.TYPE_HOME, "", "", false); } return this; }
From source file:org.runnerup.view.DetailActivity.java
void fillHeaderData() { // Fields from the database (projection) // Must include the _id column for the adapter to work String[] from = new String[] { DB.ACTIVITY.START_TIME, DB.ACTIVITY.DISTANCE, DB.ACTIVITY.TIME, DB.ACTIVITY.COMMENT, DB.ACTIVITY.SPORT }; Cursor c = mDB.query(DB.ACTIVITY.TABLE, from, "_id == " + mID, null, null, null, null, null); c.moveToFirst();//from w w w. j av a 2 s.co m ContentValues tmp = DBHelper.get(c); c.close(); long st = 0; if (tmp.containsKey(DB.ACTIVITY.START_TIME)) { st = tmp.getAsLong(DB.ACTIVITY.START_TIME); setTitle("RunnerUp - " + formatter.formatDateTime(Formatter.TXT_LONG, st)); } float d = 0; if (tmp.containsKey(DB.ACTIVITY.DISTANCE)) { d = tmp.getAsFloat(DB.ACTIVITY.DISTANCE); activityDistance.setText(formatter.formatDistance(Formatter.TXT_LONG, (long) d)); } else { activityDistance.setText(""); } float t = 0; if (tmp.containsKey(DB.ACTIVITY.TIME)) { t = tmp.getAsFloat(DB.ACTIVITY.TIME); activityTime.setText(formatter.formatElapsedTime(Formatter.TXT_SHORT, (long) t)); } else { activityTime.setText(""); } if (d != 0 && t != 0) { activityPace.setText(formatter.formatPace(Formatter.TXT_LONG, t / d)); } else { activityPace.setText(""); } if (tmp.containsKey(DB.ACTIVITY.COMMENT)) { notes.setText(tmp.getAsString(DB.ACTIVITY.COMMENT)); } if (tmp.containsKey(DB.ACTIVITY.SPORT)) { sport.setValue(tmp.getAsInteger(DB.ACTIVITY.SPORT)); } }
From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return;//ww w . ja va 2 s . c o m } final boolean force = intent.getBooleanExtra("force", false); try { Locale loc = Locale.getDefault(); String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B if (lang == null || lang.length() == 0) { lang = ""; } int serverVersion = intent.getIntExtra("serverVersion", -1); boolean fromPush = serverVersion != -1; JSONObject versionJson = null; if (!fromPush) { versionJson = getVersion(true); serverVersion = versionJson.getInt("version"); } int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1); final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, ""); if (serverVersion <= localVersion && !force && lang.equals(localLanguage) && !LOCAL_DEFINITION_TESTING) { // don't update DebugLog.i("Nothing new, not updating"); return; } // update but don't notify about it. boolean firstLaunchNoUpdate = ((localVersion == -1 && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage)); if (!firstLaunchNoUpdate) { DebugLog.i("There are new definitions available!"); } handleAuthorMessage(versionJson, lang, intent, fromPush); InputStream is = getIS(URL_TICKETS_ID); try { String json = readResult(is); JSONObject o = new JSONObject(json); JSONArray array = o.getJSONArray("tickets"); final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase(); for (int i = 0; i < array.length(); i++) { final JSONObject city = array.getJSONObject(i); try { final ContentValues cv = new ContentValues(); cv.put(Cities._ID, city.getInt("id")); cv.put(Cities.CITY, getStringLocValue(city, lang, "city")); if (city.has("city_pubtran")) { cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran")); } cv.put(Cities.COUNTRY, city.getString("country")); cv.put(Cities.CURRENCY, city.getString("currency")); cv.put(Cities.DATE_FORMAT, city.getString("dateFormat")); cv.put(Cities.IDENTIFICATION, city.getString("identification")); cv.put(Cities.LAT, city.getDouble("lat")); cv.put(Cities.LON, city.getDouble("lon")); cv.put(Cities.NOTE, getStringLocValue(city, lang, "note")); cv.put(Cities.NUMBER, city.getString("number")); cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom")); cv.put(Cities.P_DATE_TO, city.getString("pDateTo")); cv.put(Cities.P_HASH, city.getString("pHash")); cv.put(Cities.PRICE, city.getString("price")); cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote")); cv.put(Cities.REQUEST, city.getString("request")); cv.put(Cities.VALIDITY, city.getInt("validity")); if (city.has("confirmReq")) { cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq")); } if (city.has("confirm")) { cv.put(Cities.CONFIRM, city.getString("confirm")); } final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers"); for (int j = 0; j < additionalNumbers.length() && j < 3; j++) { cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j)); } db.beginTransaction(); int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv, Cities._ID + " = " + cv.getAsInteger(Cities._ID), null); if (count == 0) { db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv); } db.setTransactionSuccessful(); getContentResolver().notifyChange(Cities.CONTENT_URI, null); } finally { if (db.inTransaction()) { db.endTransaction(); } } } Preferences.set(c, Preferences.DATA_VERSION, serverVersion); Preferences.set(c, Preferences.DATA_LANGUAGE, lang); if (!firstLaunchNoUpdate && !fromPush) { final int finalServerVersion = serverVersion; mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(UpdateService.this, getString(R.string.cities_update_completed, finalServerVersion), Toast.LENGTH_LONG).show(); } }); } if (LOCAL_DEFINITION_TESTING) { DebugLog.w( "Local definition testing - data updated from assets - must be removed in production!"); } } finally { is.close(); } } catch (IOException e) { DebugLog.e("IOException when calling update: " + e.getMessage(), e); } catch (JSONException e) { DebugLog.e("JSONException when calling update: " + e.getMessage(), e); } }
From source file:jen.jobs.application.DownloadDataTask.java
public void downloadProfile(final View v) { String[] profileUrl = { Jenjobs.PROFILE_URL + "?access-token=" + accessToken }; GetRequest g = new GetRequest(); g.execute(profileUrl);//from w w w . j a v a2 s. c o m g.setResultListener(new GetRequest.ResultListener() { @Override public void processResultArray(JSONArray result) { } @Override public void processResult(JSONObject success) { if (success != null) { int js_profile_id; TableAddress tblAddress = new TableAddress(context); ContentValues cv = new ContentValues(); try { success.remove("_link"); // remove _link cv.put("access_token", String.valueOf(accessToken)); cv.put("_id", String.valueOf(success.get("id"))); cv.put("email", String.valueOf(success.get("email"))); cv.put("username", String.valueOf(success.get("username"))); cv.put("name", String.valueOf(success.get("name"))); cv.put("ic_no", String.valueOf(success.get("ic_no"))); cv.put("passport_no", String.valueOf(success.get("passport_no"))); cv.put("mobile_no", String.valueOf(success.get("mobile_no"))); cv.put("dial_code", String.valueOf(success.get("dial_code"))); cv.put("gender", String.valueOf(success.get("gender"))); cv.put("dob", String.valueOf(success.get("dob"))); cv.put("pr", String.valueOf(success.get("pr"))); cv.put("resume_file", String.valueOf(success.get("resume_file"))); cv.put("photo_file", String.valueOf(success.get("photo_file"))); cv.put("access", String.valueOf(success.get("access"))); cv.put("status", String.valueOf(success.get("status"))); cv.put("country_id", String.valueOf(success.get("country_id"))); cv.put("driving_license", String.valueOf(success.get("driving_license"))); cv.put("transport", String.valueOf(success.get("transport"))); cv.put("js_jobseek_status_id", String.valueOf(success.get("js_jobseek_status_id"))); cv.put("availability", String.valueOf(success.get("availability"))); cv.put("availability_unit", String.valueOf(success.get("availability_unit"))); //cv.put("address", String.valueOf(success.get("address"))); cv.put("no_work_exp", String.valueOf(success.get("no_work_exp"))); cv.put("additional_info", String.valueOf(success.get("info"))); cv.put("created_at", String.valueOf(success.get("created_at"))); cv.put("updated_at", String.valueOf(success.get("updated_at"))); tableProfile.addProfile(cv); js_profile_id = cv.getAsInteger("_id"); //Log.e("js_profile_id", String.valueOf(js_profile_id)); SharedPreferences.Editor spEdit = sharedPref.edit(); spEdit.putInt("js_profile_id", js_profile_id); spEdit.apply(); // default address ContentValues cv2 = new ContentValues(); cv2.put("address1", ""); cv2.put("address2", ""); cv2.put("postcode", 0); cv2.put("city_id", 0); cv2.put("city_name", ""); cv2.put("state_id", 0); cv2.put("state_name", ""); cv2.put("country_id", 0); cv2.put("updated_at", Jenjobs.date(null, null, null)); tblAddress.addAddress(cv2); if (v != null) { TextView name = (TextView) v.findViewById(R.id.fullName); TextView email = (TextView) v.findViewById(R.id.email); TextView mobile_no = (TextView) v.findViewById(R.id.mobile_no); TextView ic_no = (TextView) v.findViewById(R.id.ic_no); TextView gender = (TextView) v.findViewById(R.id.gender); TextView dob = (TextView) v.findViewById(R.id.dob); TextView country = (TextView) v.findViewById(R.id.country); ImageView profileImage = (ImageView) v.findViewById(R.id.profile_image); name.setText(String.valueOf(success.get("name"))); email.setText(String.valueOf(success.get("email"))); mobile_no.setText(String.valueOf(success.get("mobile_no"))); ic_no.setText(String.valueOf(success.get("ic_no"))); gender.setText(String.valueOf(success.get("gender"))); country.setText(String.valueOf(success.get("country"))); String _dob = String.valueOf(success.get("dob")); if (_dob != null) { dob.setText(Jenjobs.date(_dob, null, "yyyy-MM-dd")); } if (String.valueOf(success.get("photo_file")) != null) { new ImageLoad(String.valueOf(success.get("photo_file")), profileImage).execute(); } } // save address String address = String.valueOf(success.get("address")); if (address != null && !address.equals("null")) { JSONObject jsonAddr = new JSONObject(address); ContentValues cv3 = new ContentValues(); cv3.put("address1", jsonAddr.getString("address1")); cv3.put("address2", jsonAddr.getString("address2")); String postCodeStr = jsonAddr.getString("postcode"); int postCode = 0; if (postCodeStr != null && !postCodeStr.equals("null")) { postCode = Integer.valueOf(postCodeStr); } cv3.put("postcode", postCode); cv3.put("city_id", jsonAddr.getInt("city_id")); cv3.put("city_name", jsonAddr.getString("city_name")); cv3.put("state_id", jsonAddr.getInt("state_id")); cv3.put("state_name", jsonAddr.getString("state_name")); cv3.put("country_id", jsonAddr.getInt("country_id")); cv3.put("updated_at", jsonAddr.getString("date_updated")); tblAddress.updateAddress(cv3); } // end save address } catch (JSONException e) { Log.e("profileExcp", e.getMessage()); } } } }); }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
/** * Inserts an object into the database and flags it to be sent by * the transport layer.//from w w w. j ava2 s.c om */ long addToFeed(String appId, String feedName, ContentValues values) { try { JSONObject json = new JSONObject(values.getAsString(DbObject.JSON)); String type = values.getAsString(DbObject.TYPE); long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1; long timestamp = new Date().getTime(); json.put(DbObjects.TYPE, type); json.put(DbObjects.FEED_NAME, feedName); json.put(DbObjects.SEQUENCE_ID, nextSeqId); json.put(DbObjects.TIMESTAMP, timestamp); json.put(DbObjects.APP_ID, appId); // Explicit column referencing avoids database errors. ContentValues cv = new ContentValues(); cv.put(DbObject._ID, getNextId()); cv.put(DbObject.APP_ID, appId); cv.put(DbObject.FEED_NAME, feedName); cv.put(DbObject.CONTACT_ID, Contact.MY_ID); cv.put(DbObject.TYPE, type); cv.put(DbObject.SEQUENCE_ID, nextSeqId); cv.put(DbObject.JSON, json.toString()); cv.put(DbObject.TIMESTAMP, timestamp); cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime()); if (values.containsKey(DbObject.RAW)) { cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW)); } if (values.containsKey(DbObject.KEY_INT)) { cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT)); } 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 objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv); if (json.has(DbObjects.TARGET_HASH)) { long hashA = json.optLong(DbObjects.TARGET_HASH); long idA = objIdForHash(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, objId, relation); } } Uri objUri = DbObject.uriForObj(objId); mContext.getContentResolver().registerContentObserver(objUri, false, new ModificationObserver(mContext, objId)); return objId; } catch (Exception e) { // TODO, too spammy //e.printStackTrace(System.err); return -1; } }
From source file:com.ichi2.anki.provider.CardContentProvider.java
@Override public Uri insert(Uri uri, ContentValues values) { Timber.d("CardContentProvider.insert"); Collection col = CollectionHelper.getInstance().getCol(getContext()); if (col == null) { return null; }// www. j a v a 2 s . c o m // Find out what data the user is requesting int match = sUriMatcher.match(uri); switch (match) { case NOTES: { /* Insert new note with specified fields and tags */ Long modelId = values.getAsLong(FlashCardsContract.Note.MID); String flds = values.getAsString(FlashCardsContract.Note.FLDS); String tags = values.getAsString(FlashCardsContract.Note.TAGS); // Create empty note com.ichi2.libanki.Note newNote = new com.ichi2.libanki.Note(col, col.getModels().get(modelId)); // Set fields String[] fldsArray = Utils.splitFields(flds); // Check that correct number of flds specified if (fldsArray.length != newNote.getFields().length) { throw new IllegalArgumentException("Incorrect flds argument : " + flds); } for (int idx = 0; idx < fldsArray.length; idx++) { newNote.setField(idx, fldsArray[idx]); } // Set tags if (tags != null) { newNote.setTagsFromStr(tags); } // Add to collection col.addNote(newNote); return Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, Long.toString(newNote.getId())); } case NOTES_ID: // Note ID is generated automatically by libanki throw new IllegalArgumentException("Not possible to insert note with specific ID"); case NOTES_ID_CARDS: // Cards are generated automatically by libanki throw new IllegalArgumentException("Not possible to insert cards directly (only through NOTES)"); case NOTES_ID_CARDS_ORD: // Cards are generated automatically by libanki throw new IllegalArgumentException("Not possible to insert cards directly (only through NOTES)"); case MODELS: // Get input arguments String modelName = values.getAsString(FlashCardsContract.Model.NAME); String css = values.getAsString(FlashCardsContract.Model.CSS); Long did = values.getAsLong(FlashCardsContract.Model.DECK_ID); String fieldNames = values.getAsString(FlashCardsContract.Model.FIELD_NAMES); Integer numCards = values.getAsInteger(FlashCardsContract.Model.NUM_CARDS); // Throw exception if required fields empty if (modelName == null || fieldNames == null || numCards == null) { throw new IllegalArgumentException("Model name, field_names, and num_cards can't be empty"); } // Create a new model Models mm = col.getModels(); JSONObject newModel = mm.newModel(modelName); try { // Add the fields String[] allFields = Utils.splitFields(fieldNames); for (String f : allFields) { mm.addField(newModel, mm.newField(f)); } // Add some empty card templates for (int idx = 0; idx < numCards; idx++) { JSONObject t = mm.newTemplate("Card " + (idx + 1)); t.put("qfmt", String.format("{{%s}}", allFields[0])); String answerField = allFields[0]; if (allFields.length > 1) { answerField = allFields[1]; } t.put("afmt", String.format("{{FrontSide}}\\n\\n<hr id=answer>\\n\\n{{%s}}", answerField)); mm.addTemplate(newModel, t); } // Add the CSS if specified if (css != null) { newModel.put("css", css); } // Add the did if specified if (did != null) { newModel.put("did", did); } // Add the model to collection (from this point on edits will require a full-sync) mm.add(newModel); mm.save(newModel); // TODO: is this necessary? // Get the mid and return a URI String mid = Long.toString(newModel.getLong("id")); return Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, mid); } catch (ConfirmModSchemaException e) { // This exception should never be thrown when inserting new models Timber.e(e, "Unexpected ConfirmModSchema exception adding new model %s", modelName); throw new IllegalArgumentException("ConfirmModSchema exception adding new model " + modelName); } catch (JSONException e) { Timber.e(e, "Could not set a field of new model %s", modelName); return null; } case MODELS_ID: // Model ID is generated automatically by libanki throw new IllegalArgumentException("Not possible to insert model with specific ID"); case MODELS_ID_TEMPLATES: // Adding new templates after the model is created could require a full-sync throw new IllegalArgumentException("Templates can only be added at the time of model insertion"); case MODELS_ID_TEMPLATES_ID: // Adding new templates after the model is created could require a full-sync throw new IllegalArgumentException("Templates can only be added at the time of model insertion"); case SCHEDULE: // Doesn't make sense to insert an object into the schedule table throw new IllegalArgumentException("Not possible to perform insert operation on schedule"); case DECKS: // Insert new deck with specified name String deckName = values.getAsString(FlashCardsContract.Deck.DECK_NAME); did = col.getDecks().id(deckName); return Uri.withAppendedPath(FlashCardsContract.Deck.CONTENT_ALL_URI, Long.toString(did)); case DECK_SELECTED: // Can't have more than one selected deck throw new IllegalArgumentException("Selected deck can only be queried and updated"); case DECKS_ID: // Deck ID is generated automatically by libanki throw new IllegalArgumentException("Not possible to insert deck with specific ID"); default: // Unknown URI type throw new IllegalArgumentException("uri " + uri + " is not supported"); } }
From source file:org.runnerup.export.SyncManager.java
@SuppressWarnings("null") public Synchronizer add(ContentValues config) { if (config == null) { Log.e(getClass().getName(), "Add null!"); assert (false); return null; }/* w w w . j a v a 2 s .com*/ String synchronizerName = config.getAsString(DB.ACCOUNT.NAME); if (synchronizerName == null) { Log.e(getClass().getName(), "name not found!"); return null; } if (synchronizers.containsKey(synchronizerName)) { return synchronizers.get(synchronizerName); } Synchronizer synchronizer = null; if (synchronizerName.contentEquals(RunKeeperSynchronizer.NAME)) { synchronizer = new RunKeeperSynchronizer(this); } else if (synchronizerName.contentEquals(GarminSynchronizer.NAME)) { synchronizer = new GarminSynchronizer(this); } else if (synchronizerName.contentEquals(FunBeatSynchronizer.NAME)) { synchronizer = new FunBeatSynchronizer(this); } else if (synchronizerName.contentEquals(MapMyRunSynchronizer.NAME)) { synchronizer = new MapMyRunSynchronizer(this); } else if (synchronizerName.contentEquals(NikePlusSynchronizer.NAME)) { synchronizer = new NikePlusSynchronizer(this); } else if (synchronizerName.contentEquals(JoggSESynchronizer.NAME)) { synchronizer = new JoggSESynchronizer(this); } else if (synchronizerName.contentEquals(EndomondoSynchronizer.NAME)) { synchronizer = new EndomondoSynchronizer(this); } else if (synchronizerName.contentEquals(RunningAHEADSynchronizer.NAME)) { synchronizer = new RunningAHEADSynchronizer(this); } else if (synchronizerName.contentEquals(RunnerUpLiveSynchronizer.NAME)) { synchronizer = new RunnerUpLiveSynchronizer(mContext); } else if (synchronizerName.contentEquals(DigifitSynchronizer.NAME)) { synchronizer = new DigifitSynchronizer(this); } else if (synchronizerName.contentEquals(StravaSynchronizer.NAME)) { synchronizer = new StravaSynchronizer(this); } else if (synchronizerName.contentEquals(FacebookSynchronizer.NAME)) { synchronizer = new FacebookSynchronizer(mContext, this); } else if (synchronizerName.contentEquals(GooglePlusSynchronizer.NAME)) { synchronizer = new GooglePlusSynchronizer(this); } else if (synchronizerName.contentEquals(RuntasticSynchronizer.NAME)) { synchronizer = new RuntasticSynchronizer(this); } else if (synchronizerName.contentEquals(GoogleFitSynchronizer.NAME)) { synchronizer = new GoogleFitSynchronizer(mContext, this); } else if (synchronizerName.contentEquals(RunningFreeOnlineSynchronizer.NAME)) { synchronizer = new RunningFreeOnlineSynchronizer(); } if (synchronizer != null) { if (!config.containsKey(DB.ACCOUNT.FLAGS)) { if (BuildConfig.DEBUG) { String s = null; s.charAt(3); } } synchronizer.init(config); synchronizer.setAuthNotice(config.getAsInteger(Constants.DB.ACCOUNT.AUTH_NOTICE)); synchronizers.put(synchronizerName, synchronizer); synchronizersById.put(synchronizer.getId(), synchronizer); } return synchronizer; }
From source file:com.ichi2.anki.provider.CardContentProvider.java
@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { Timber.d("CardContentProvider.update"); Collection col = CollectionHelper.getInstance().getCol(getContext()); if (col == null) { return 0; }/*w w w.j a v a2 s . c o m*/ // Find out what data the user is requesting int match = sUriMatcher.match(uri); int updated = 0; // Number of updated entries (return value) switch (match) { case NOTES: throw new IllegalArgumentException("Not possible to update notes directly (only through data URI)"); case NOTES_ID: { /* Direct access note details */ Note currentNote = getNoteFromUri(uri, col); // the key of the ContentValues contains the column name // the value of the ContentValues contains the row value. Set<Map.Entry<String, Object>> valueSet = values.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { String key = entry.getKey(); if (key.equals(FlashCardsContract.Note.FLDS)) { // Update FLDS Timber.d("CardContentProvider: flds update..."); String newFldsEncoded = (String) entry.getValue(); String[] flds = Utils.splitFields(newFldsEncoded); // Check that correct number of flds specified if (flds.length != currentNote.getFields().length) { throw new IllegalArgumentException("Incorrect flds argument : " + newFldsEncoded); } // Update the note for (int idx = 0; idx < flds.length; idx++) { currentNote.setField(idx, flds[idx]); } updated++; } else if (key.equals(FlashCardsContract.Note.TAGS)) { // Update tags Timber.d("CardContentProvider: tags update..."); currentNote.setTagsFromStr((String) entry.getValue()); updated++; } else { // Unsupported column throw new IllegalArgumentException("Unsupported column: " + key); } } Timber.d("CardContentProvider: Saving note..."); currentNote.flush(); break; } case NOTES_ID_CARDS: // TODO: To be implemented throw new UnsupportedOperationException("Not yet implemented"); // break; case NOTES_ID_CARDS_ORD: { Card currentCard = getCardFromUri(uri, col); boolean isDeckUpdate = false; long did = -1; // the key of the ContentValues contains the column name // the value of the ContentValues contains the row value. Set<Map.Entry<String, Object>> valueSet = values.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { // Only updates on deck id is supported String key = entry.getKey(); isDeckUpdate = key.equals(FlashCardsContract.Card.DECK_ID); did = values.getAsLong(key); } /* now update the card */ if ((isDeckUpdate) && (did >= 0)) { Timber.d("CardContentProvider: Moving card to other deck..."); col.getDecks().flush(); currentCard.setDid(did); currentCard.flush(); updated++; } else { // User tries an operation that is not (yet?) supported. throw new IllegalArgumentException("Currently only updates of decks are supported"); } break; } case MODELS: throw new IllegalArgumentException("Cannot update models in bulk"); case MODELS_ID: // Get the input parameters String newModelName = values.getAsString(FlashCardsContract.Model.NAME); String newCss = values.getAsString(FlashCardsContract.Model.CSS); String newDid = values.getAsString(FlashCardsContract.Model.DECK_ID); String newFieldList = values.getAsString(FlashCardsContract.Model.FIELD_NAMES); if (newFieldList != null) { // Changing the field names would require a full-sync throw new IllegalArgumentException("Field names cannot be changed via provider"); } // Get the original note JSON JSONObject model = col.getModels().get(getModelIdFromUri(uri, col)); try { // Update model name and/or css if (newModelName != null) { model.put("name", newModelName); updated++; } if (newCss != null) { model.put("css", newCss); updated++; } if (newDid != null) { model.put("did", newDid); updated++; } col.getModels().save(model); } catch (JSONException e) { Timber.e(e, "JSONException updating model"); } break; case MODELS_ID_TEMPLATES: throw new IllegalArgumentException("Cannot update templates in bulk"); case MODELS_ID_TEMPLATES_ID: Long mid = values.getAsLong(CardTemplate.MODEL_ID); Integer ord = values.getAsInteger(CardTemplate.ORD); String name = values.getAsString(CardTemplate.NAME); String qfmt = values.getAsString(CardTemplate.QUESTION_FORMAT); String afmt = values.getAsString(CardTemplate.ANSWER_FORMAT); String bqfmt = values.getAsString(CardTemplate.BROWSER_QUESTION_FORMAT); String bafmt = values.getAsString(CardTemplate.BROWSER_ANSWER_FORMAT); // Throw exception if read-only fields are included if (mid != null || ord != null) { throw new IllegalArgumentException("Can update mid or ord"); } // Update the model try { Integer templateOrd = Integer.parseInt(uri.getLastPathSegment()); JSONObject existingModel = col.getModels().get(getModelIdFromUri(uri, col)); JSONArray templates = existingModel.getJSONArray("tmpls"); JSONObject template = templates.getJSONObject(templateOrd); if (name != null) { template.put("name", name); updated++; } if (qfmt != null) { template.put("qfmt", qfmt); updated++; } if (afmt != null) { template.put("afmt", afmt); updated++; } if (bqfmt != null) { template.put("bqfmt", bqfmt); updated++; } if (bafmt != null) { template.put("bafmt", bafmt); updated++; } // Save the model templates.put(templateOrd, template); existingModel.put("tmpls", templates); col.getModels().save(existingModel, true); } catch (JSONException e) { throw new IllegalArgumentException("Model is malformed", e); } break; case SCHEDULE: { Set<Map.Entry<String, Object>> valueSet = values.valueSet(); int cardOrd = -1; long noteID = -1; int ease = -1; long timeTaken = -1; for (Map.Entry<String, Object> entry : valueSet) { String key = entry.getKey(); if (key.equals(FlashCardsContract.ReviewInfo.NOTE_ID)) { noteID = values.getAsLong(key); } else if (key.equals(FlashCardsContract.ReviewInfo.CARD_ORD)) { cardOrd = values.getAsInteger(key); } else if (key.equals(FlashCardsContract.ReviewInfo.EASE)) { ease = values.getAsInteger(key); } else if (key.equals(FlashCardsContract.ReviewInfo.TIME_TAKEN)) { timeTaken = values.getAsLong(key); } } if (cardOrd != -1 && noteID != -1) { Card cardToAnswer = getCard(noteID, cardOrd, col); if (cardToAnswer != null) { answerCard(col, col.getSched(), cardToAnswer, ease, timeTaken); updated++; } else { Timber.e( "Requested card with noteId %d and cardOrd %d was not found. Either the provided " + "noteId/cardOrd were wrong or the card has been deleted in the meantime.", noteID, cardOrd); } } break; } case DECKS: throw new IllegalArgumentException("Can't update decks in bulk"); case DECKS_ID: throw new UnsupportedOperationException("Not yet implemented"); case DECK_SELECTED: { Set<Map.Entry<String, Object>> valueSet = values.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { String key = entry.getKey(); if (key.equals(FlashCardsContract.Deck.DECK_ID)) { long deckId = values.getAsLong(key); if (selectDeckWithCheck(col, deckId)) { updated++; } } } break; } default: // Unknown URI type throw new IllegalArgumentException("uri " + uri + " is not supported"); } return updated; }