List of usage examples for android.content ContentResolver update
public final int update(@RequiresPermission.Write @NonNull Uri uri, @Nullable ContentValues values, @Nullable String where, @Nullable String[] selectionArgs)
From source file:gov.wa.wsdot.android.wsdot.service.CamerasSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/* w w w.ja v a 2 s. c o m*/ long now = System.currentTimeMillis(); boolean shouldUpdate = true; String responseString = ""; /** * Check the cache table for the last time data was downloaded. If we are within * the allowed time period, don't sync, otherwise get fresh data from the server. */ try { cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "cameras" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaDays = (now - lastUpdated) / DateUtils.DAY_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaDays + " day(s)"); shouldUpdate = (Math.abs(now - lastUpdated) > (7 * DateUtils.DAY_IN_MILLIS)); } } finally { if (cursor != null) { cursor.close(); } } // Ability to force a refresh of camera data. boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false); if (shouldUpdate || forceUpdate) { List<Integer> starred = new ArrayList<Integer>(); starred = getStarred(); try { URL url = new URL(CAMERAS_URL); URLConnection urlConn = url.openConnection(); BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream()); GZIPInputStream gzin = new GZIPInputStream(bis); InputStreamReader is = new InputStreamReader(gzin); BufferedReader in = new BufferedReader(is); String jsonFile = ""; String line; while ((line = in.readLine()) != null) jsonFile += line; in.close(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("cameras"); JSONArray items = result.getJSONArray("items"); List<ContentValues> cams = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); ContentValues cameraData = new ContentValues(); cameraData.put(Cameras.CAMERA_ID, item.getString("id")); cameraData.put(Cameras.CAMERA_TITLE, item.getString("title")); cameraData.put(Cameras.CAMERA_URL, item.getString("url")); cameraData.put(Cameras.CAMERA_LATITUDE, item.getString("lat")); cameraData.put(Cameras.CAMERA_LONGITUDE, item.getString("lon")); cameraData.put(Cameras.CAMERA_HAS_VIDEO, item.getString("video")); cameraData.put(Cameras.CAMERA_ROAD_NAME, item.getString("roadName")); if (starred.contains(Integer.parseInt(item.getString("id")))) { cameraData.put(Cameras.CAMERA_IS_STARRED, 1); } cams.add(cameraData); } // Purge existing cameras covered by incoming data resolver.delete(Cameras.CONTENT_URI, null, null); // Bulk insert all the new cameras resolver.bulkInsert(Cameras.CONTENT_URI, cams.toArray(new ContentValues[cams.size()])); // Update the cache table with the time we did the update ContentValues values = new ContentValues(); values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis()); resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "cameras" }); responseString = "OK"; } catch (Exception e) { Log.e(DEBUG_TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.CAMERAS_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:org.servalproject.maps.bridge.AutoUploadReceiver.java
private void doUpload(Context context, Intent intent, String uploadUrl) { // get the URI of the new POI Uri mNewPoiUri = (Uri) intent.getParcelableExtra("uri"); if (mNewPoiUri == null) { Log.w(sTag, "missing uri data in intent"); return;/*from w ww . j a v a 2 s . co m*/ } // get the poi data ContentResolver mContentResolver = context.getContentResolver(); Cursor mCursor = mContentResolver.query(mNewPoiUri, null, null, null, null); // check on what was returned if (mCursor == null) { Log.w(sTag, "unable to lookup new POI details"); return; } if (mCursor.getCount() == 0) { Log.w(sTag, "unable to lookup new POI details"); return; } if (!mCursor.moveToFirst()) { Log.w(sTag, "unable to lookup new POI details"); return; } /* * TODO refactor this code to make it more portable * including the same code in the BatchUploadTask class */ ContentValues mContentValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(mCursor, mContentValues); String mJsonData = null; // convert the data to JSON try { mJsonData = BasicJsonMaker.makePoiJson(mContentValues); } catch (JSONException e) { Log.e(sTag, "unable to encode JSON data for '" + mCursor.getString(mCursor.getColumnIndex(PointsOfInterestContract.Table._ID)), e); mJsonData = null; } // build the log entry mContentValues = new ContentValues(); mContentValues.put(LogContract.Table.POI_ID, mCursor.getString(mCursor.getColumnIndex(PointsOfInterestContract.Table._ID))); mContentValues.put(LogContract.Table.POI_TITLE, mCursor.getString(mCursor.getColumnIndex(PointsOfInterestContract.Table.TITLE))); mContentValues.put(LogContract.Table.JSON_CONTENT, mJsonData); // add the appropriate upload flag if (mJsonData == null) { mContentValues.put(LogContract.Table.UPLOAD_STATUS, LogContract.INVALID_JSON_FLAG); } else { mContentValues.put(LogContract.Table.UPLOAD_STATUS, LogContract.UPLOAD_PENDING_FLAG); } mContentValues.put(LogContract.Table.TIMESTAMP, System.currentTimeMillis()); // add the table row Uri mNewLogRecord = mContentResolver.insert(LogContract.CONTENT_URI, mContentValues); /* * upload the new record */ ContentValues mUpdateValues; String[] mProjection = new String[2]; mProjection[0] = LogContract.Table._ID; mProjection[1] = LogContract.Table.JSON_CONTENT; mCursor = mContentResolver.query(mNewLogRecord, mProjection, null, null, null); if (mCursor == null || mCursor.getCount() == 0 || mCursor.moveToFirst() == false) { Log.w(sTag, "unable to lookup new log entry"); return; } boolean mUploadStatus = BasicHttpUploader.doBasicPost(uploadUrl, mCursor.getString(mCursor.getColumnIndex(mProjection[1]))); // define selection criteria for the update String mSelection = LogContract.Table._ID + " = ?"; String[] mSelectionArgs = new String[1]; mSelectionArgs[0] = mCursor.getString(mCursor.getColumnIndex(LogContract.Table._ID)); if (mUploadStatus) { // the upload was a success mUpdateValues = new ContentValues(); mUpdateValues.put(LogContract.Table.UPLOAD_STATUS, LogContract.UPLOAD_SUCCESS_FLAG); mUpdateValues.put(LogContract.Table.TIMESTAMP, System.currentTimeMillis()); } else { // the upload was a failure mUpdateValues = new ContentValues(); mUpdateValues.put(LogContract.Table.UPLOAD_STATUS, LogContract.UPLOAD_FAILED_FLAG); mUpdateValues.put(LogContract.Table.TIMESTAMP, System.currentTimeMillis()); } // update the log entry mContentResolver.update(LogContract.CONTENT_URI, mUpdateValues, mSelection, mSelectionArgs); }
From source file:org.m2x.rssreader.service.FetcherService.java
private int refreshFeed(String feedId) { RssAtomParser handler = null;/*from ww w . j a va 2 s. co m*/ ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null); if (!cursor.moveToFirst()) { cursor.close(); return 0; } int urlPosition = cursor.getColumnIndex(FeedColumns.URL); int titlePosition = cursor.getColumnIndex(FeedColumns.NAME); int fetchmodePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE); int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE); int iconPosition = cursor.getColumnIndex(FeedColumns.ICON); int retrieveFullTextPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT); HttpURLConnection connection = null; try { String feedUrl = cursor.getString(urlPosition); connection = NetworkUtils.setupConnection(feedUrl); String contentType = connection.getContentType(); int fetchMode = cursor.getInt(fetchmodePosition); handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), feedId, cursor.getString(titlePosition), feedUrl, cursor.getInt(retrieveFullTextPosition) == 1); handler.setFetchImages(PrefUtils.getBoolean(PrefUtils.FETCH_PICTURES, true)); if (fetchMode == 0) { if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) { BufferedReader reader = new BufferedReader( new InputStreamReader(NetworkUtils.getConnectionInputStream(connection))); String line; int posStart = -1; while ((line = reader.readLine()) != null) { if (line.contains(HTML_BODY)) { break; } else { Matcher matcher = FEED_LINK_PATTERN.matcher(line); if (matcher.find()) { // not "while" as only one link is needed line = matcher.group(); posStart = line.indexOf(HREF); if (posStart > -1) { String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10)) .replace("&", "&"); ContentValues values = new ContentValues(); if (url.startsWith("/")) { int index = feedUrl.indexOf('/', 8); if (index > -1) { url = feedUrl.substring(0, index) + url; } else { url = feedUrl + url; } } else if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) { url = feedUrl + '/' + url; } values.put(FeedColumns.URL, url); cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null); connection.disconnect(); connection = NetworkUtils.setupConnection(url); contentType = connection.getContentType(); break; } } } } // this indicates a badly configured feed if (posStart == -1) { connection.disconnect(); connection = NetworkUtils.setupConnection(feedUrl); contentType = connection.getContentType(); } } if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8)); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException usee) { fetchMode = FETCHMODE_REENCODE; } } else { fetchMode = FETCHMODE_REENCODE; } } else { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(NetworkUtils.getConnectionInputStream(connection))); char[] chars = new char[20]; int length = bufferedReader.read(chars); String xmlDescription = new String(chars, 0, length); connection.disconnect(); connection = NetworkUtils.setupConnection(connection.getURL()); int start = xmlDescription != null ? xmlDescription.indexOf(ENCODING) : -1; if (start > -1) { try { Xml.findEncodingByName( xmlDescription.substring(start + 10, xmlDescription.indexOf('"', start + 11))); fetchMode = FETCHMODE_DIRECT; } catch (UnsupportedEncodingException usee) { fetchMode = FETCHMODE_REENCODE; } } else { // absolutely no encoding information found fetchMode = FETCHMODE_DIRECT; } } ContentValues values = new ContentValues(); values.put(FeedColumns.FETCH_MODE, fetchMode); cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null); } switch (fetchMode) { default: case FETCHMODE_DIRECT: { if (contentType != null) { int index = contentType.indexOf(CHARSET); int index2 = contentType.indexOf(';', index); InputStream inputStream = NetworkUtils.getConnectionInputStream(connection); Xml.parse(inputStream, Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8)), handler); } else { InputStreamReader reader = new InputStreamReader( NetworkUtils.getConnectionInputStream(connection)); Xml.parse(reader, handler); } break; } case FETCHMODE_REENCODE: { ByteArrayOutputStream ouputStream = new ByteArrayOutputStream(); InputStream inputStream = NetworkUtils.getConnectionInputStream(connection); byte[] byteBuffer = new byte[4096]; int n; while ((n = inputStream.read(byteBuffer)) > 0) { ouputStream.write(byteBuffer, 0, n); } String xmlText = ouputStream.toString(); int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1; if (start > -1) { Xml.parse(new StringReader(new String(ouputStream.toByteArray(), xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler); } else { // use content type if (contentType != null) { int index = contentType.indexOf(CHARSET); if (index > -1) { int index2 = contentType.indexOf(';', index); try { StringReader reader = new StringReader(new String(ouputStream.toByteArray(), index2 > -1 ? contentType.substring(index + 8, index2) : contentType.substring(index + 8))); Xml.parse(reader, handler); } catch (Exception ignored) { } } else { StringReader reader = new StringReader(new String(ouputStream.toByteArray())); Xml.parse(reader, handler); } } } break; } } connection.disconnect(); } catch (FileNotFoundException e) { if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) { ContentValues values = new ContentValues(); // resets the fetchmode to determine it again later values.put(FeedColumns.FETCH_MODE, 0); values.put(FeedColumns.ERROR, getString(R.string.error_feed_error)); cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null); } } catch (Throwable e) { if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) { ContentValues values = new ContentValues(); // resets the fetchmode to determine it again later values.put(FeedColumns.FETCH_MODE, 0); values.put(FeedColumns.ERROR, e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process)); cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null); } } finally { /* check and optionally find favicon */ try { if (handler != null && cursor.getBlob(iconPosition) == null) { String feedLink = handler.getFeedLink(); if (feedLink != null) { NetworkUtils.retrieveFavicon(this, new URL(feedLink), feedId); } else { NetworkUtils.retrieveFavicon(this, connection.getURL(), feedId); } } } catch (Throwable ignored) { } if (connection != null) { connection.disconnect(); } } cursor.close(); return handler != null ? handler.getNewCount() : 0; }
From source file:gov.wa.wsdot.android.wsdot.service.FerriesSchedulesSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/*w w w . j av a 2s . c om*/ long now = System.currentTimeMillis(); boolean shouldUpdate = true; String responseString = ""; DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a"); /** * Check the cache table for the last time data was downloaded. If we are within * the allowed time period, don't sync, otherwise get fresh data from the server. */ try { cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED }, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_schedules" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min"); shouldUpdate = (Math.abs(now - lastUpdated) > (30 * DateUtils.MINUTE_IN_MILLIS)); } } finally { if (cursor != null) { cursor.close(); } } // Ability to force a refresh of camera data. boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false); if (shouldUpdate || forceUpdate) { List<Integer> starred = new ArrayList<Integer>(); starred = getStarred(); try { URL url = new URL(FERRIES_SCHEDULES_URL); URLConnection urlConn = url.openConnection(); BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream()); GZIPInputStream gzin = new GZIPInputStream(bis); InputStreamReader is = new InputStreamReader(gzin); BufferedReader in = new BufferedReader(is); String jsonFile = ""; String line; while ((line = in.readLine()) != null) jsonFile += line; in.close(); JSONArray items = new JSONArray(jsonFile); List<ContentValues> schedules = new ArrayList<ContentValues>(); int numItems = items.length(); for (int i = 0; i < numItems; i++) { JSONObject item = items.getJSONObject(i); ContentValues schedule = new ContentValues(); schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ID, item.getInt("RouteID")); schedule.put(FerriesSchedules.FERRIES_SCHEDULE_TITLE, item.getString("Description")); schedule.put(FerriesSchedules.FERRIES_SCHEDULE_DATE, item.getString("Date")); schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ALERT, item.getString("RouteAlert")); schedule.put(FerriesSchedules.FERRIES_SCHEDULE_UPDATED, dateFormat .format(new Date(Long.parseLong(item.getString("CacheDate").substring(6, 19))))); if (starred.contains(item.getInt("RouteID"))) { schedule.put(FerriesSchedules.FERRIES_SCHEDULE_IS_STARRED, 1); } schedules.add(schedule); } // Purge existing travel times covered by incoming data resolver.delete(FerriesSchedules.CONTENT_URI, null, null); // Bulk insert all the new travel times resolver.bulkInsert(FerriesSchedules.CONTENT_URI, schedules.toArray(new ContentValues[schedules.size()])); // Update the cache table with the time we did the update ContentValues values = new ContentValues(); values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis()); resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?", new String[] { "ferries_schedules" }); responseString = "OK"; } catch (Exception e) { Log.e(DEBUG_TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.FERRIES_SCHEDULES_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:gov.wa.wsdot.android.wsdot.service.TravelTimesSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/*from w w w . j av a 2s . c om*/ long now = System.currentTimeMillis(); boolean shouldUpdate = true; String responseString = ""; /** * Check the cache table for the last time data was downloaded. If we are within * the allowed time period, don't sync, otherwise get fresh data from the server. */ try { cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED }, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "travel_times" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min"); shouldUpdate = (Math.abs(now - lastUpdated) > (5 * DateUtils.MINUTE_IN_MILLIS)); } } finally { if (cursor != null) { cursor.close(); } } // Ability to force a refresh of camera data. boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false); if (shouldUpdate || forceUpdate) { List<Integer> starred = new ArrayList<Integer>(); starred = getStarred(); try { URL url = new URL(TRAVEL_TIMES_URL); URLConnection urlConn = url.openConnection(); BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream()); GZIPInputStream gzin = new GZIPInputStream(bis); InputStreamReader is = new InputStreamReader(gzin); BufferedReader in = new BufferedReader(is); String jsonFile = ""; String line; while ((line = in.readLine()) != null) jsonFile += line; in.close(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("traveltimes"); JSONArray items = result.getJSONArray("items"); List<ContentValues> times = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); ContentValues timesValues = new ContentValues(); timesValues.put(TravelTimes.TRAVEL_TIMES_TITLE, item.getString("title")); timesValues.put(TravelTimes.TRAVEL_TIMES_CURRENT, item.getInt("current")); timesValues.put(TravelTimes.TRAVEL_TIMES_AVERAGE, item.getInt("average")); timesValues.put(TravelTimes.TRAVEL_TIMES_DISTANCE, item.getString("distance") + " miles"); timesValues.put(TravelTimes.TRAVEL_TIMES_ID, Integer.parseInt(item.getString("routeid"))); timesValues.put(TravelTimes.TRAVEL_TIMES_UPDATED, item.getString("updated")); if (starred.contains(Integer.parseInt(item.getString("routeid")))) { timesValues.put(TravelTimes.TRAVEL_TIMES_IS_STARRED, 1); } times.add(timesValues); } // Purge existing travel times covered by incoming data resolver.delete(TravelTimes.CONTENT_URI, null, null); // Bulk insert all the new travel times resolver.bulkInsert(TravelTimes.CONTENT_URI, times.toArray(new ContentValues[times.size()])); // Update the cache table with the time we did the update ContentValues values = new ContentValues(); values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis()); resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?", new String[] { "travel_times" }); responseString = "OK"; } catch (Exception e) { Log.e(DEBUG_TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.TRAVEL_TIMES_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:com.android.providers.contacts.ContactsSyncAdapter.java
protected void sendClientPhotos(SyncContext context, ContentProvider clientDiffs, Object syncInfo, SyncResult syncResult) {//from ww w .j av a 2 s . co m Entry entry = new MediaEntry(); GDataServiceClient client = getGDataServiceClient(); String authToken = getAuthToken(); ContentResolver cr = getContext().getContentResolver(); final String account = getAccount(); Cursor c = clientDiffs.query(Photos.CONTENT_URI, null /* all columns */, null /* no where */, null /* no where args */, null /* default sort order */); try { int personColumn = c.getColumnIndexOrThrow(Photos.PERSON_ID); int dataColumn = c.getColumnIndexOrThrow(Photos.DATA); int numRows = c.getCount(); while (c.moveToNext()) { if (mSyncCanceled) { if (Config.LOGD) Log.d(TAG, "stopping since the sync was canceled"); break; } entry.clear(); context.setStatusText("Updating, " + (numRows - 1) + " to go"); cursorToBaseEntry(entry, account, c); String editUrl = entry.getEditUri(); if (TextUtils.isEmpty(editUrl)) { if (Config.LOGD) { Log.d(TAG, "skipping photo edit for unsynced contact"); } continue; } // Send the request and receive the response InputStream inputStream = null; byte[] imageData = c.getBlob(dataColumn); if (imageData != null) { inputStream = new ByteArrayInputStream(imageData); } Uri photoUri = Uri.withAppendedPath(People.CONTENT_URI, c.getString(personColumn) + "/" + Photos.CONTENT_DIRECTORY); try { if (inputStream != null) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Updating photo " + entry.toString()); } ++mPhotoUploads; client.updateMediaEntry(editUrl, inputStream, IMAGE_MIME_TYPE, authToken); } else { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Deleting photo " + entry.toString()); } client.deleteEntry(editUrl, authToken); } // Mark that this photo is no longer dirty. The next time we sync (which // should be soon), we will get the new version of the photo and whether // or not there is a new one to download (e.g. if we deleted our version // yet there is an evergreen version present). ContentValues values = new ContentValues(); values.put(Photos.EXISTS_ON_SERVER, inputStream == null ? 0 : 1); values.put(Photos._SYNC_DIRTY, 0); if (cr.update(photoUri, values, null /* no where */, null /* no where args */) != 1) { Log.e(TAG, "error updating photo " + photoUri + " with values " + values); syncResult.stats.numParseExceptions++; } else { syncResult.stats.numUpdates++; } continue; } catch (ParseException e) { Log.e(TAG, "parse error during update of " + ", skipping"); syncResult.stats.numParseExceptions++; } catch (IOException e) { if (Config.LOGD) { Log.d(TAG, "io error during update of " + entry.toString() + ", skipping"); } syncResult.stats.numIoExceptions++; } catch (HttpException e) { switch (e.getStatusCode()) { case HttpException.SC_UNAUTHORIZED: if (syncResult.stats.numAuthExceptions == 0) { if (Config.LOGD) { Log.d(TAG, "auth error during update of " + entry + ", skipping"); } } syncResult.stats.numAuthExceptions++; try { GoogleLoginServiceBlockingHelper.invalidateAuthToken(getContext(), authToken); } catch (GoogleLoginServiceNotFoundException e1) { if (Config.LOGD) { Log.d(TAG, "could not invalidate auth token", e1); } } return; case HttpException.SC_CONFLICT: if (Config.LOGD) { Log.d(TAG, "conflict detected during update of " + entry + ", skipping"); } syncResult.stats.numConflictDetectedExceptions++; break; case HttpException.SC_BAD_REQUEST: case HttpException.SC_FORBIDDEN: case HttpException.SC_NOT_FOUND: case HttpException.SC_INTERNAL_SERVER_ERROR: default: if (Config.LOGD) { Log.d(TAG, "error " + e.getMessage() + " during update of " + entry.toString() + ", skipping"); } syncResult.stats.numIoExceptions++; } } } } finally { c.close(); } }
From source file:gov.wa.wsdot.android.wsdot.service.HighwayAlertsSyncService.java
@SuppressLint("SimpleDateFormat") @Override// ww w. j a va2s .co m protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null; long now = System.currentTimeMillis(); boolean shouldUpdate = true; String responseString = ""; DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a"); /** * Check the cache table for the last time data was downloaded. If we are within * the allowed time period, don't sync, otherwise get fresh data from the server. */ try { cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "highway_alerts" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min"); shouldUpdate = (Math.abs(now - lastUpdated) > (5 * DateUtils.MINUTE_IN_MILLIS)); } } finally { if (cursor != null) { cursor.close(); } } // Tapping the refresh button will force a data refresh. boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false); if (shouldUpdate || forceUpdate) { try { URL url = new URL(HIGHWAY_ALERTS_URL); URLConnection urlConn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String jsonFile = ""; String line; while ((line = in.readLine()) != null) { jsonFile += line; } in.close(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("alerts"); JSONArray items = result.getJSONArray("items"); List<ContentValues> alerts = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); JSONObject startRoadwayLocation = item.getJSONObject("StartRoadwayLocation"); ContentValues alertData = new ContentValues(); alertData.put(HighwayAlerts.HIGHWAY_ALERT_ID, item.getString("AlertID")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_HEADLINE, item.getString("HeadlineDescription")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_CATEGORY, item.getString("EventCategory")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_PRIORITY, item.getString("Priority")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_LATITUDE, startRoadwayLocation.getString("Latitude")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_LONGITUDE, startRoadwayLocation.getString("Longitude")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_ROAD_NAME, startRoadwayLocation.getString("RoadName")); alertData.put(HighwayAlerts.HIGHWAY_ALERT_LAST_UPDATED, dateFormat .format(new Date(Long.parseLong(item.getString("LastUpdatedTime").substring(6, 19))))); alerts.add(alertData); } // Purge existing highway alerts covered by incoming data resolver.delete(HighwayAlerts.CONTENT_URI, null, null); // Bulk insert all the new highway alerts resolver.bulkInsert(HighwayAlerts.CONTENT_URI, alerts.toArray(new ContentValues[alerts.size()])); // Update the cache table with the time we did the update ContentValues values = new ContentValues(); values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis()); resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "highway_alerts" }); responseString = "OK"; } catch (Exception e) { Log.e(DEBUG_TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.HIGHWAY_ALERTS_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:edu.mit.mobile.android.locast.data.Sync.java
/** * Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network, * attempt to sync.//from w ww. j a v a 2s. c o m * Either c or cvNet can be null, but not both. * @param c A cursor pointing to the data item. Null is OK here. * @param jsonObject JSON object for the item as loaded from the network. null is OK here. * @param sync An empty JsonSyncableItem object. * @param publicPath TODO * * @return True if the item has been modified on either end. * @throws IOException */ private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync, SyncProgressNotifier syncProgress, String publicPath) throws SyncException, IOException { boolean modified = false; boolean needToCloseCursor = false; boolean toSyncIsIndex = false; final SyncMap syncMap = sync.getSyncMap(); Uri locUri = null; final Uri origToSync = toSync; ContentValues cvNet = null; final Context context = getApplicationContext(); final ContentResolver cr = context.getContentResolver(); if (jsonObject != null) { if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { // we successfully loaded it from the 'net, but toSync is really for local URIs. Erase it. toSync = sync.getContentUri(); if (toSync == null) { if (DEBUG) { Log.w(TAG, "cannot get local URI for " + origToSync + ". Skipping..."); } return false; } } try { cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap); } catch (final Exception e) { final SyncException se = new SyncException("Problem loading JSON object."); se.initCause(e); throw se; } } final String contentType = cr.getType(toSync); if (c != null) { if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID))) .buildUpon().query(null).build(); toSyncIsIndex = true; } else { locUri = toSync; } // skip any items already sync'd if (mLastUpdated.isUpdatedRecently(locUri)) { return false; } final int draftCol = c.getColumnIndex(TaggableItem._DRAFT); if (draftCol != -1 && c.getInt(draftCol) != 0) { if (DEBUG) { Log.d(TAG, locUri + " is marked a draft. Not syncing."); } return false; } syncMap.onPreSyncItem(cr, locUri, c); } else if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { // strip any query strings toSync = toSync.buildUpon().query(null).build(); } // if (c != null){ // MediaProvider.dumpCursorToLog(c, sync.getFullProjection()); // } // when the PUBLIC_URI is null, that means it's only local final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1; if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")) { // new content on the local side only. Gotta publish. try { jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap); if (publicPath == null) { publicPath = MediaProvider.getPostPath(this, locUri); } if (DEBUG) { Log.d(TAG, "Posting " + locUri + " to " + publicPath); } // The response from a post to create a new item should be the newly created item, // which contains the public ID that we need. jsonObject = nc.postJson(publicPath, jsonObject); final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap); if (cr.update(locUri, cvUpdate, null, null) == 1) { // at this point, server and client should be in sync. mLastUpdated.markUpdated(locUri); if (DEBUG) { Log.i(TAG, "Hooray! " + locUri + " has been posted succesfully."); } } else { Log.e(TAG, "update of " + locUri + " failed"); } modified = true; } catch (final Exception e) { final SyncException se = new SyncException(getString(R.string.error_sync_no_post)); se.initCause(e); throw se; } // only on the remote side, so pull it in. } else if (c == null && cvNet != null) { if (DEBUG) { Log.i(TAG, "Only on the remote side, using network-provided values."); } final String[] params = { cvNet.getAsString(JsonSyncableItem._PUBLIC_URI) }; c = cr.query(toSync, sync.getFullProjection(), JsonSyncableItem._PUBLIC_URI + "=?", params, null); needToCloseCursor = true; if (!c.moveToFirst()) { locUri = cr.insert(toSync, cvNet); modified = true; } else { locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID))) .buildUpon().query(null).build(); syncMap.onPreSyncItem(cr, locUri, c); } } // we've now found data on both sides, so sync them. if (!modified && c != null) { publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI)); try { if (cvNet == null) { try { if (publicPath == null && toSyncIsIndex && !MediaProvider.canSync(locUri)) { // At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems). // If we can't sync individual items, it's possible that the index is paged or the item has been deleted. if (DEBUG) { Log.w(TAG, "Asked to sync " + locUri + " but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date."); } return false; } else { if (mLastUpdated.isUpdatedRecently(nc.getFullUri(publicPath))) { if (DEBUG) { Log.d(TAG, "already sync'd! " + publicPath); } return false; } if (jsonObject == null) { jsonObject = nc.getObject(publicPath); } cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap); } } catch (final HttpResponseException hre) { if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND) { final SyncItemDeletedException side = new SyncItemDeletedException(locUri); side.initCause(hre); throw side; } } } if (cvNet == null) { Log.e(TAG, "got null values from fromJSON() on item " + locUri + ": " + (jsonObject != null ? jsonObject.toString() : "<< no json object >>")); return false; } final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE)); final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE))); if (netLastModified.equals(locLastModified)) { // same! yay! We don't need to do anything. if (DEBUG) { Log.d("LocastSync", locUri + " doesn't need to sync."); } } else if (netLastModified.after(locLastModified)) { // remote is more up to date, update! cr.update(locUri, cvNet, null, null); if (DEBUG) { Log.d("LocastSync", cvNet + " is newer than " + locUri); } modified = true; } else if (netLastModified.before(locLastModified)) { // local is more up to date, propagate! jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap)); if (DEBUG) { Log.d("LocastSync", cvNet + " is older than " + locUri); } modified = true; } mLastUpdated.markUpdated(nc.getFullUri(publicPath)); } catch (final JSONException e) { final SyncException se = new SyncException( "Item sync error for path " + publicPath + ": invalid JSON."); se.initCause(e); throw se; } catch (final NetworkProtocolException e) { final SyncException se = new SyncException( "Item sync error for path " + publicPath + ": " + e.getHttpResponseMessage()); se.initCause(e); throw se; } finally { if (needToCloseCursor) { c.close(); needToCloseCursor = false; } } } if (needToCloseCursor) { c.close(); } if (locUri == null) { throw new RuntimeException("Never got a local URI for a sync'd item."); } // two calls are made in two different contexts. Which context you use depends on the application. syncMap.onPostSyncItem(context, locUri, jsonObject, modified); sync.onPostSyncItem(context, locUri, jsonObject, modified); mLastUpdated.markUpdated(locUri); // needed for things that may have requested a sync with a different URI than what was eventually produced. if (origToSync != locUri) { mLastUpdated.markUpdated(origToSync); cr.notifyChange(origToSync, null); } return modified; }
From source file:com.indeema.mail.ui.AbstractActivityController.java
/** * Displays a the auto-advance dialog, and when the user makes a selection, the preference is * stored, and the specified operation is run. *///from w w w. j a v a2 s . c o m private void displayAutoAdvanceDialogAndPerformAction(final Runnable operation) { final String[] autoAdvanceDisplayOptions = mContext.getResources() .getStringArray(R.array.prefEntries_autoAdvance); final String[] autoAdvanceOptionValues = mContext.getResources() .getStringArray(R.array.prefValues_autoAdvance); final String defaultValue = mContext.getString(R.string.prefDefault_autoAdvance); int initialIndex = 0; for (int i = 0; i < autoAdvanceOptionValues.length; i++) { if (defaultValue.equals(autoAdvanceOptionValues[i])) { initialIndex = i; break; } } final OnClickListener listClickListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichItem) { final String autoAdvanceValue = autoAdvanceOptionValues[whichItem]; final int autoAdvanceValueInt = UIProvider.AutoAdvance.getAutoAdvanceInt(autoAdvanceValue); mAccount.settings.setAutoAdvanceSetting(autoAdvanceValueInt); // Save the user's setting final ContentValues values = new ContentValues(1); values.put(AccountColumns.SettingsColumns.AUTO_ADVANCE, autoAdvanceValue); final ContentResolver resolver = mContext.getContentResolver(); resolver.update(mAccount.updateSettingsUri, values, null, null); // Dismiss the dialog, as clicking the items in the list doesn't close the // dialog. dialog.dismiss(); if (operation != null) { operation.run(); } } }; new AlertDialog.Builder(mActivity.getActivityContext()).setTitle(R.string.auto_advance_help_title) .setSingleChoiceItems(autoAdvanceDisplayOptions, initialIndex, listClickListener) .setPositiveButton(null, null).create().show(); }
From source file:com.chen.mail.ui.AbstractActivityController.java
/** * Displays a the auto-advance dialog, and when the user makes a selection, the preference is * stored, and the specified operation is run. *//* w ww.j av a 2s . c om*/ private void displayAutoAdvanceDialogAndPerformAction(final Runnable operation) { final String[] autoAdvanceDisplayOptions = mContext.getResources() .getStringArray(R.array.prefEntries_autoAdvance); final String[] autoAdvanceOptionValues = mContext.getResources() .getStringArray(R.array.prefValues_autoAdvance); final String defaultValue = mContext.getString(R.string.prefDefault_autoAdvance); int initialIndex = 0; for (int i = 0; i < autoAdvanceOptionValues.length; i++) { if (defaultValue.equals(autoAdvanceOptionValues[i])) { initialIndex = i; break; } } final DialogInterface.OnClickListener listClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichItem) { final String autoAdvanceValue = autoAdvanceOptionValues[whichItem]; final int autoAdvanceValueInt = UIProvider.AutoAdvance.getAutoAdvanceInt(autoAdvanceValue); mAccount.settings.setAutoAdvanceSetting(autoAdvanceValueInt); // Save the user's setting final ContentValues values = new ContentValues(1); values.put(AccountColumns.SettingsColumns.AUTO_ADVANCE, autoAdvanceValue); final ContentResolver resolver = mContext.getContentResolver(); resolver.update(mAccount.updateSettingsUri, values, null, null); // Dismiss the dialog, as clicking the items in the list doesn't close the // dialog. dialog.dismiss(); if (operation != null) { operation.run(); } } }; new AlertDialog.Builder(mActivity.getActivityContext()).setTitle(R.string.auto_advance_help_title) .setSingleChoiceItems(autoAdvanceDisplayOptions, initialIndex, listClickListener) .setPositiveButton(null, null).create().show(); }