List of usage examples for android.content ContentValues remove
public void remove(String key)
From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java
private Uri insertArtwork(@NonNull final Uri uri, final ContentValues values) { Context context = getContext(); if (context == null) { return null; }//from ww w .j a v a 2 s.co m if (values == null) { throw new IllegalArgumentException("Invalid ContentValues: must not be null"); } if (!values.containsKey(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME) || TextUtils.isEmpty(values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME))) { throw new IllegalArgumentException("Initial values must contain component name: " + values); } // Check to make sure the component name is valid ComponentName componentName = ComponentName .unflattenFromString(values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME)); if (componentName == null) { throw new IllegalArgumentException("Invalid component name: " + values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME)); } // Make sure they are using the short string format values.put(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME, componentName.flattenToShortString()); // Ensure the app inserting the artwork is either Muzei or the same app as the source String callingPackageName = getCallingPackage(); if (!context.getPackageName().equals(callingPackageName) && !TextUtils.equals(callingPackageName, componentName.getPackageName())) { throw new IllegalArgumentException("Calling package name (" + callingPackageName + ") must match the source's package name (" + componentName.getPackageName() + ")"); } if (values.containsKey(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT)) { String viewIntentString = values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT); Intent viewIntent; try { if (!TextUtils.isEmpty(viewIntentString)) { // Make sure it is a valid Intent URI viewIntent = Intent.parseUri(viewIntentString, Intent.URI_INTENT_SCHEME); // Make sure we can construct a PendingIntent for the Intent PendingIntent.getActivity(context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT); } } catch (URISyntaxException e) { Log.w(TAG, "Removing invalid View Intent: " + viewIntentString, e); values.remove(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT); } catch (RuntimeException e) { // This is actually meant to catch a FileUriExposedException, but you can't // have catch statements for exceptions that don't exist at your minSdkVersion Log.w(TAG, "Removing invalid View Intent that contains a file:// URI: " + viewIntentString, e); values.remove(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT); } } // Ensure the related source has been added to the database. // This should be true in 99.9% of cases, but the insert will fail if this isn't true Cursor sourceQuery = querySource(MuzeiContract.Sources.CONTENT_URI, new String[] { BaseColumns._ID }, MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME + "=?", new String[] { componentName.flattenToShortString() }, null); if (sourceQuery == null || sourceQuery.getCount() == 0) { ContentValues initialValues = new ContentValues(); initialValues.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME, componentName.flattenToShortString()); insertSource(MuzeiContract.Sources.CONTENT_URI, initialValues); } if (sourceQuery != null) { sourceQuery.close(); } values.put(MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED, System.currentTimeMillis()); final SQLiteDatabase db = databaseHelper.getWritableDatabase(); long rowId = db.insert(MuzeiContract.Artwork.TABLE_NAME, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, values); // If the insert succeeded, the row ID exists. if (rowId > 0) { // Creates a URI with the artwork ID pattern and the new row ID appended to it. final Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowId); File artwork = getCacheFileForArtworkUri(artworkUri); if (artwork != null && artwork.exists()) { // The image already exists so we'll notifyChange() to say the new artwork is ready // Otherwise, this will be called when the file is written with openFile() // using this Uri and the actual artwork is written successfully notifyChange(artworkUri); } return artworkUri; } // If the insert didn't succeed, then the rowID is <= 0 throw new SQLException("Failed to insert row into " + uri); }
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. jav a2s .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)); }
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 a 2s . 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 updateTopTeams() { LOGD(TAG, "starting 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 v a2 s.c o m } // first, check last update time long lastUpdate = PrefUtils.lastTeamsUpdate(this); long currentTime = TimeUtils.getUTCTime(); // if last update is less than 1 hour old, boot user to cursorloader op. if (currentTime - lastUpdate < 60000 * 60) { LOGD(TAG, "returnning due to too soon"); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); return; } // else // use local broadcast manager to show loading indicator LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_UPDATING)); final String BASE_URL = "http://www.gosugamers.net/dota2/rankings"; final String TEAM_LINK_BASE_URL = "http://www.gosugamers.net/dota2/teams/"; // we see what teams are in top 50. (httpreq -> gosugamers) 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); ContentValues[] teamRanks = new ContentValues[50]; HashMap<ContentValues, Future<String>> newTeamInfo = new HashMap<ContentValues, Future<String>>(); HashMap<ContentValues, Future<String>> updateTeamInfo = new HashMap<ContentValues, Future<String>>(); int i = 0; 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, "Have team already?"); if (!cursor.getString(0).contentEquals(teamName) || !cursor.getString(1).contentEquals(teamUrl)) { LOGD(TAG, "Team has updated values."); updateTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } } // -> if not present, add to update queue. else { LOGD(TAG, "Do team update"); newTeamInfo.put(contentValues, executorService.submit(new TeamGetter(teamUrl))); } // LOGD(TAG, "\n" + // "data-id: " + teamId + "\n" + // "team-name: " + teamName + "\n" + // "team-url: " + teamUrl); teamRanks[i] = new ContentValues(); teamRanks[i].put(MatchContract.TeamRankEntry._ID, i + 1); teamRanks[i].put(MatchContract.TeamRankEntry.COLUMN_TEAM_ID, teamId); cursor.close(); i++; } 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 = updateTeamInfo.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()])); getContentResolver().bulkInsert(MatchContract.TeamRankEntry.CONTENT_URI, teamRanks); } 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, // MatchContract.TeamRankEntry.TABLE_NAME + "." + MatchContract.TeamRankEntry._ID // }; // // String sortOrder = // MatchContract.TeamRankEntry.TABLE_NAME + "." + // MatchContract.TeamRankEntry._ID + " ASC"; // // Cursor c = getContentResolver().query( // MatchContract.TeamEntry.TOP_50_URI, // projection, // null, // null, // sortOrder // ); // // while (c.moveToNext()) { // String teamPrintOut = // "Rank: " + c.getInt(5) + "\n" + // "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 + "/UTT", teamPrintOut); // } // // c.close(); // use local broadcast manager to hide loading indicator // and signal that cursorloader for top50 can happen. PrefUtils.setLastTeamUpdate(this, currentTime); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(STATUS_COMPLETED)); }
From source file:com.zns.comicdroid.activity.Edit.java
private void UpdateComics() { final ContentValues values = new ContentValues(); final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this); String title = mEtTitle.getText().toString().trim(); if (title.toLowerCase(Locale.ENGLISH).startsWith("the ")) { title = title.substring(4) + ", The"; }/* ww w. j av a 2s .c o m*/ if (mComics != null && mComics.size() > 1) { if (!isEmpty(mEtTitle)) values.put("Title", title); if (!isEmpty(mEtSubtitle)) values.put("SubTitle", mEtSubtitle.getText().toString()); if (!isEmpty(mEtAuthor)) values.put("Author", mEtAuthor.getText().toString()); if (!isEmpty(mEtIllustrator)) values.put("Illustrator", mEtIllustrator.getText().toString()); if (!isEmpty(mEtPublisher)) values.put("Publisher", mEtPublisher.getText().toString()); if (mSpGroup.getSelectedItemPosition() > 0) { Group g = (Group) mSpGroup.getSelectedItem(); values.put("GroupId", g.getId()); } } else { //Strings values.put("Title", title); values.put("SubTitle", mEtSubtitle.getText().toString()); values.put("Author", mEtAuthor.getText().toString()); values.put("Illustrator", mEtIllustrator.getText().toString()); values.put("Publisher", mEtPublisher.getText().toString()); values.put("Issues", mEtIssues.getText().toString()); //Integers if (!isEmpty(mEtIssue)) { if (isValidInt(mEtIssue.getText().toString())) { values.put("Issue", Integer.parseInt(mEtIssue.getText().toString())); } else { Toast.makeText(this, R.string.edit_issueerror, Toast.LENGTH_LONG).show(); return; } } else { values.putNull("Issue"); } if (!isEmpty(mEtPageCount)) { if (isValidInt(mEtPageCount.getText().toString())) { values.put("PageCount", Integer.parseInt(mEtPageCount.getText().toString())); } else { Toast.makeText(this, R.string.edit_pagecounterror, Toast.LENGTH_LONG).show(); return; } } else { values.putNull("PageCount"); } //Dates try { if (!isEmpty(mEtPublished)) { values.put("PublishDate", getDBHelper().GetDateStamp(mEtPublished.getText().toString(), dateFormat)); } else { values.putNull("PublishDate"); } if (!isEmpty(mEtAdded)) { values.put("AddedDate", getDBHelper().GetDateStamp(mEtAdded.getText().toString(), dateFormat)); } else { values.putNull("AddedDate"); } } catch (ParseException e) { Toast.makeText(this, getString(R.string.edit_dateerror) + " " + dateFormat.format(new Date()), Toast.LENGTH_LONG).show(); return; } //Image if (mNewImage != null) { values.put("ImageUrl", ""); values.put("Image", new File(mNewImage).getName()); } //Group if (mSpGroup.getSelectedItemPosition() > 0) { Group g = (Group) mSpGroup.getSelectedItem(); values.put("GroupId", g.getId()); } else { values.putNull("GroupId"); } } if (mComics != null) { //UPDATE StringBuilder sbWhere = new StringBuilder("_id IN ("); String[] ids = new String[mComics.size()]; int i = 0; for (Comic c : mComics) { sbWhere.append("?,"); ids[i] = Integer.toString(c.getId()); i++; } sbWhere.setLength(sbWhere.length() - 1); sbWhere.append(")"); getDBHelper().update("tblBooks", values, sbWhere.toString(), ids); } else { //INSERT if (!values.containsKey("AddedDate") || values.get("AddedDate") == null) { values.remove("AddedDate"); values.put("AddedDate", (int) (System.currentTimeMillis() / 1000L)); } long id = getDBHelper().insert("tblBooks", values); Comic comic = getDBHelper().getComic((int) id); if (comic != null) { mComics = new ArrayList<Comic>(); mComics.add(comic); } } //Backup BackupManager m = new BackupManager(this); m.dataChanged(); setResult(RESULT_OK); Toast.makeText(this, getResources().getString(R.string.edit_done), Toast.LENGTH_LONG).show(); }
From source file:org.kontalk.sync.Syncer.java
/** * The actual sync procedure./*from w w w .j av a2 s .co m*/ * This one uses the slowest method ever: it first checks for every phone * number in all contacts and it sends them to the server. Once a response * is received, it deletes all the raw contacts created by us and then * recreates only the ones the server has found a match for. */ public void performSync(Context context, Account account, String authority, ContentProviderClient provider, ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException { final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>(); final List<String> jidList = new ArrayList<>(); // resync users database Log.v(TAG, "resyncing users database"); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // update users database Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build(); try { int count = usersProvider.update(uri, new ContentValues(), null, null); Log.d(TAG, "users database resynced (" + count + ")"); } catch (Exception e) { Log.e(TAG, "error resyncing users database - aborting sync", e); syncResult.databaseError = true; return; } // query all contacts Cursor cursor; try { cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE, new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null); } catch (Exception e) { Log.e(TAG, "error querying users database - aborting sync", e); syncResult.databaseError = true; return; } while (cursor.moveToNext()) { if (mCanceled) { cursor.close(); throw new OperationCanceledException(); } String jid = cursor.getString(0); String number = cursor.getString(1); String lookupKey = cursor.getString(2); // avoid to send duplicates to the server if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid), new RawPhoneNumberEntry(lookupKey, number, jid)) == null) jidList.add(jid); } cursor.close(); if (mCanceled) throw new OperationCanceledException(); // empty contacts :-| if (jidList.size() == 0) { // delete all Kontalk raw contacts try { syncResult.stats.numDeletes += deleteAll(account, provider); } catch (Exception e) { Log.e(TAG, "contact delete error", e); syncResult.databaseError = true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { syncResult.stats.numDeletes += deleteProfile(account, provider); } catch (Exception e) { Log.e(TAG, "profile delete error", e); syncResult.databaseError = true; } } commit(usersProvider, syncResult); } else { final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext); // register presence broadcast receiver PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this); IntentFilter f = new IntentFilter(); f.addAction(MessageCenterService.ACTION_PRESENCE); f.addAction(MessageCenterService.ACTION_ROSTER_MATCH); f.addAction(MessageCenterService.ACTION_PUBLICKEY); f.addAction(MessageCenterService.ACTION_BLOCKLIST); f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY); f.addAction(MessageCenterService.ACTION_CONNECTED); lbm.registerReceiver(receiver, f); // request current connection status MessageCenterService.requestConnectionStatus(mContext); // wait for the service to complete its job synchronized (this) { // wait for connection try { wait(MAX_WAIT_TIME); } catch (InterruptedException e) { // simulate canceled operation mCanceled = true; } } lbm.unregisterReceiver(receiver); // last chance to quit if (mCanceled) throw new OperationCanceledException(); List<PresenceItem> res = receiver.getResponse(); if (res != null) { ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); // TODO operations.size() could be used instead (?) int op = 0; // this is the time - delete all Kontalk raw contacts try { syncResult.stats.numDeletes += deleteAll(account, provider); } catch (Exception e) { Log.e(TAG, "contact delete error", e); syncResult.databaseError = true; return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { syncResult.stats.numDeletes += deleteProfile(account, provider); } catch (Exception e) { Log.e(TAG, "profile delete error", e); syncResult.databaseError = true; } } ContentValues registeredValues = new ContentValues(); registeredValues.put(Users.REGISTERED, 1); for (int i = 0; i < res.size(); i++) { PresenceItem entry = res.get(i); if (entry.discarded) continue; final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from)); if (data != null && data.lookupKey != null) { // add contact addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number, data.jid, operations, op++); } else { syncResult.stats.numSkippedEntries++; } // update fields try { String status = entry.status; if (!TextUtils.isEmpty(status)) registeredValues.put(Users.STATUS, status); else registeredValues.putNull(Users.STATUS); if (entry.timestamp >= 0) registeredValues.put(Users.LAST_SEEN, entry.timestamp); else registeredValues.putNull(Users.LAST_SEEN); if (entry.publicKey != null) { try { PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey); // trust our own key blindly int trustLevel = Authenticator.isSelfJID(mContext, entry.from) ? MyUsers.Keys.TRUST_VERIFIED : -1; // update keys table immediately Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel); // no data from system contacts, use name from public key if (data == null) { PGPUserID uid = PGP.parseUserId(pubKey, XmppStringUtils.parseDomain(entry.from)); if (uid != null) { registeredValues.put(Users.DISPLAY_NAME, uid.getName()); } } } catch (Exception e) { Log.w(TAG, "unable to parse public key", e); } } else { // use roster name if no contact data available if (data == null && entry.rosterName != null) { registeredValues.put(Users.DISPLAY_NAME, entry.rosterName); } } // blocked status registeredValues.put(Users.BLOCKED, entry.blocked); // user JID as reported by the server registeredValues.put(Users.JID, entry.from); /* * Since UsersProvider.resync inserted the user row * using our server name, it might have changed because * of what the server reported. We already put into the * values the new JID, but we need to use the old one * in the where condition so we will have a match. */ String origJid; if (data != null) origJid = XMPPUtils.createLocalJID(mContext, XmppStringUtils.parseLocalpart(entry.from)); else origJid = entry.from; usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?", new String[] { origJid }); // clear data registeredValues.remove(Users.DISPLAY_NAME); // if this is our own contact, trust our own key later if (Authenticator.isSelfJID(mContext, entry.from)) { // register our profile while we're at it if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // add contact addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number, data.jid, operations, op++); } } } catch (Exception e) { Log.e(TAG, "error updating users database", e); // we shall continue here... } } try { if (operations.size() > 0) provider.applyBatch(operations); syncResult.stats.numInserts += op; syncResult.stats.numEntries += op; } catch (Exception e) { Log.w(TAG, "contact write error", e); syncResult.stats.numSkippedEntries += op; /* * We do not consider system contacts failure a fatal error. * This is actually a workaround for systems with disabled permissions or * exotic firmwares. It can also protect against security 3rd party apps or * non-Android platforms, such as Jolla/Alien Dalvik. */ } commit(usersProvider, syncResult); } // timeout or error else { Log.w(TAG, "connection timeout - aborting sync"); syncResult.stats.numIoExceptions++; } } }
From source file:com.attentec.AttentecService.java
/** * Parse one user from JSONObject and save to database. * @param user the JSONObject to parse/*from ww w . jav a2 s . c om*/ * @param username the username of ourselves * @return which userid whas updated * @throws JSONException if parsing failed */ @SuppressWarnings("unchecked") private String parseJSONUser(final JSONObject user, final String username) throws JSONException { //Log.d(TAG, "parsing JSON user"); ContentValues cv = new ContentValues(); String updated = new String(); //go over all fields Iterator<String> it = user.keys(); boolean isSelf = false; while (it.hasNext()) { String key = it.next(); String value = null; try { value = user.getString(key); } catch (JSONException e) { Log.e(TAG, "JSONException user field: " + key); throw e; } if (key.equals("id")) { key = "_id"; updated = value; } else if (key.equals("photo_url")) { //check if there is a valid photo String newPhotoUpdatedAt = null; try { newPhotoUpdatedAt = cleanDate(user.getString("photo_updated_at")); } catch (JSONException e) { Log.e(TAG, "Could not parse photo_updated_at."); continue; } if (newPhotoUpdatedAt == null) { //no photo exists, so we don't need to save one //Log.d(TAG, "No photo exists"); continue; } Long userId = null; try { userId = Long.parseLong(user.getString("id")); } catch (NumberFormatException e) { Log.e(TAG, "Could not parse user id from server."); continue; } catch (JSONException e3) { Log.e(TAG, "Could not parse user id from server."); continue; } //check if the user already exists if (!dbh.userExists(userId)) { //this is a new user, we can get a new image try { cv.put(DatabaseAdapter.KEY_PHOTO, getImage(value)); } catch (GetImageException e) { Log.e(TAG, "Could not get image: " + e.getMessage()); continue; } } //we want to check if this photo is newer than the one we have now //parse the date dfm.setLenient(true); Date newTimestamp = new Date(); try { newTimestamp = dfm.parse(newPhotoUpdatedAt); } catch (ParseException e1) { Log.e(TAG, "Could not parse newPhotoUpdatedAt: " + newPhotoUpdatedAt); continue; } String oldPhotoUpdatedAt = dbh.getContactPhotoUpdatedAt(userId); Date oldTimestamp = new Date(); if (oldPhotoUpdatedAt != null) { //parse the date try { oldTimestamp = (dfm.parse(oldPhotoUpdatedAt)); } catch (ParseException e) { Log.e(TAG, "Could not parse oldPhotoUpdatedAt: " + oldPhotoUpdatedAt); } } if ((oldTimestamp.getTime() != newTimestamp.getTime())) { Log.d(TAG, "There is a new photo, downloading..."); try { cv.put(DatabaseAdapter.KEY_PHOTO, getImage(user.get("photo_url").toString())); } catch (JSONException e) { Log.e(TAG, "Could not parse photo_url."); } catch (GetImageException e) { Log.e(TAG, "Could not get image: " + e.getMessage()); } } } else if (key.equals("username") && value.equals(username)) { //save that this is ourself, we don't want to save ourselves isSelf = true; updated = null; break; } else if (key.equals(DatabaseAdapter.KEY_LOCATION_UPDATED_AT) || key.equals(DatabaseAdapter.KEY_CONNECTED_AT) || key.equals(DatabaseAdapter.KEY_PHOTO_UPDATED_AT)) { value = cleanDate(value); } if (key != "photo_url") { cv.put(key, value); } } //check if we are ourselves if (!isSelf) { //Log.d(TAG, "Saving user: " + cv.toString()); Long existingrowId = cv.getAsLong(DatabaseAdapter.KEY_ROWID); cv.remove("photo_url"); if (!dbh.userExists(existingrowId)) { //save the user to the database dbh.addUser(cv); } else { //update the user in the database dbh.updateUser(cv, existingrowId); } } return updated; }
From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java
@Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 1 || segments.size() > 2) { throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri); }// w w w. j a v a2 s.c o m String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); String uriFormId = ((segments.size() == 2) ? segments.get(1) : null); boolean isNumericId = StringUtils.isNumeric(uriFormId); // Modify the where clause to account for the presence of // a form id. Accept either: // (1) numeric _ID value // (2) string FORM_ID value. String whereId; String[] whereIdArgs; if (uriFormId == null) { whereId = where; whereIdArgs = whereArgs; } else { if (TextUtils.isEmpty(where)) { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?"; whereIdArgs = new String[1]; whereIdArgs[0] = uriFormId; } else { whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")"; whereIdArgs = new String[whereArgs.length + 1]; whereIdArgs[0] = uriFormId; for (int i = 0; i < whereArgs.length; ++i) { whereIdArgs[i + 1] = whereArgs[i]; } } } /* * First, find out what records match this query, and if they refer to two * or more (formId,formVersion) tuples, then be sure to remove all * FORM_MEDIA_PATH references. Otherwise, if they are all for the same * tuple, and the update specifies a FORM_MEDIA_PATH, move all the * non-matching directories elsewhere. */ Integer idValue = null; String tableIdValue = null; String formIdValue = null; HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>(); boolean multiset = false; Cursor c = null; try { c = this.query(uri, null, whereId, whereIdArgs, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.getCount() >= 1) { FormIdVersion ref = null; c.moveToPosition(-1); while (c.moveToNext()) { idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, c.getColumnIndex(FormsColumns._ID)); tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); formIdValue = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); String tableId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID)); String formId = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID)); String formVersion = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_VERSION)); FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion); int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH); String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx); if (mediaPath != null) { mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath), (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS); } if (ref != null && !ref.equals(cur)) { multiset = true; break; } else { ref = cur; } } } } catch (Exception e) { log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (c != null) { c.close(); } } if (multiset) { // don't let users manually update media path // we are referring to two or more (formId,formVersion) tuples. if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH); } } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { // we are not a multiset and we are setting the media path // try to move all the existing non-matching media paths to // somewhere else... File mediaPath = ODKFileUtils.asAppFile(appName, values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)); for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) { File altPath = entry.getKey(); if (!altPath.equals(mediaPath)) { try { moveDirectory(appName, entry.getValue(), altPath); } catch (IOException e) { e.printStackTrace(); log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString()); } } } // OK. we have moved the existing form definitions elsewhere. We can // proceed with update... } // ensure that all values are correct and ignore some user-supplied // values... patchUpValues(appName, values); // Make sure that the necessary fields are all set if (values.containsKey(FormsColumns.DATE) == true) { Date today = new Date(); String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } SQLiteDatabase db = null; int count; try { // OK Finally, now do the update... db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs); db.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); log.w(t, "Unable to perform update " + uri); return 0; } finally { if (db != null) { db.endTransaction(); db.close(); } } if (count == 1) { Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(idValue)); getContext().getContentResolver().notifyChange(idUri, null); } else { getContext().getContentResolver().notifyChange(uri, null); } return count; }