List of usage examples for android.content ContentResolver query
public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder)
From source file:com.andrew.apollo.utils.MusicUtils.java
public static List<Playlist> getPlaylists(final Context context) { final List<Playlist> result = new ArrayList<>(); final ContentResolver resolver = context.getContentResolver(); final String[] projection = new String[] { BaseColumns._ID, MediaStore.Audio.PlaylistsColumns.NAME }; try {//w ww.j av a 2s . c o m final Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { result.add(new Playlist(cursor.getLong(0), cursor.getString(1))); } while (cursor.moveToNext()); } cursor.close(); } } catch (Throwable e) { LOG.error("Could not fetch playlists", e); } return result; }
From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java
/** Resolve sync file information */ private void resolveSyncFile(ContentResolver cr) { Cursor fileCursor = cr.query(itsUri, PasswdSafeContract.Files.PROJECTION, null, null, null); try {/* w w w.j a va 2 s .c o m*/ if ((fileCursor != null) && fileCursor.moveToFirst()) { itsTitle = fileCursor.getString(PasswdSafeContract.Files.PROJECTION_IDX_TITLE); } } finally { if (fileCursor != null) { fileCursor.close(); } } }
From source file:com.akop.bach.fragment.xboxlive.AchievementsFragment.java
private void loadGameDetails() { View view = getView();//from w ww . j av a 2 s.c o m if (view == null) return; if (mTitleId < 0) { view.findViewById(R.id.unselected).setVisibility(View.VISIBLE); view.findViewById(R.id.achievement_contents).setVisibility(View.GONE); } else { view.findViewById(R.id.unselected).setVisibility(View.GONE); view.findViewById(R.id.achievement_contents).setVisibility(View.VISIBLE); } if (!mShowGameTotals) return; Context context = getActivity(); ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(Games.CONTENT_URI, GamesFragment.PROJ, Games._ID + "=" + mTitleId, null, null); if (c != null) { try { if (c.moveToFirst()) { TextView tv; ImageView iv; XboxLiveGameListItem gameListItem = (XboxLiveGameListItem) view.findViewById(R.id.gameListItem); gameListItem.mBeaconSet = c.getInt(GamesFragment.GAME_BEACON_SET) != 0; gameListItem.mItemId = mTitleId; if ((tv = (TextView) view.findViewById(R.id.game_title)) != null) tv.setText(c.getString(GamesFragment.GAME_TITLE)); if ((tv = (TextView) view.findViewById(R.id.game_last_played)) != null) tv.setText(Games.getLastPlayedText(context, c.getLong(GamesFragment.GAME_LAST_PLAYED))); if ((tv = (TextView) view.findViewById(R.id.game_achievements_unlocked)) != null) tv.setText(Games.getAchievementTotalText(context, c.getInt(GamesFragment.GAME_ACH_EARNED), c.getInt(GamesFragment.GAME_ACH_TOTAL))); if ((tv = (TextView) view.findViewById(R.id.game_gp_earned)) != null) tv.setText(Games.getGamerscoreTotalText(context, c.getInt(GamesFragment.GAME_GP_EARNED), c.getInt(GamesFragment.GAME_GP_TOTAL))); iv = (ImageView) view.findViewById(R.id.game_beacon); iv.setImageResource(c.getInt(GamesFragment.GAME_BEACON_SET) != 0 ? R.drawable.beacon_on : R.drawable.beacon_off); ImageCache ic = ImageCache.getInstance(); String iconUrl = c.getString(GamesFragment.GAME_ICON_URL); Bitmap bmp; if ((bmp = ic.getCachedBitmap(iconUrl)) != null) { iv = (ImageView) view.findViewById(R.id.game_icon); iv.setImageBitmap(bmp); } else { if (iconUrl != null) { ic.requestImage(iconUrl, new OnImageReadyListener() { @Override public void onImageReady(long id, Object param, Bitmap bmp) { mHandler.post(new Runnable() { @Override public void run() { loadGameDetails(); } }); } }, 0, null, true, null); } } } } finally { c.close(); } } }
From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/*from w w w . ja v a2s . c o m*/ Context context = getContext(); App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() { @Override public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) { EarthquakeObject earthquake = response.body(); Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size()); double currentBiggest = 0.0; ContentValues notifyValues = null; for (Feature each : earthquake.getFeatures()) { ContentValues earthquakeValues = new ContentValues(); earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace()); earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId()); earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag()); earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType()); earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert()); earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime()); earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl()); earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail()); earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2)); earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0)); earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1)); LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1), each.getGeometry().getCoordinates().get(0)); LatLng location = LocationUtils.getLocation(context); earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location)); cVVector.add(earthquakeValues); if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) { currentBiggest = each.getProperties().getMag(); notifyValues = new ContentValues(earthquakeValues); notifyValues.put(EarthquakeColumns.PLACE, Utilities.formatEarthquakePlace(each.getProperties().getPlace())); } } int inserted = 0; // add to database ContentResolver resolver = context.getContentResolver(); if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray); } // Set the date to day minus one to delete old data from the database Date date = new Date(); date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS); int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?", new String[] { String.valueOf(date.getTime()) }); Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted"); sendNotification(notifyValues); } @Override public void onFailure(Call<EarthquakeObject> call, Throwable t) { Log.e(TAG, "onFailure: " + t.toString()); } }); App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() { @Override public void onResponse(Call<Rss> call, Response<Rss> response) { Channel news = response.body().getChannel(); Vector<ContentValues> cVVector = new Vector<>(news.getItem().size()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.getDefault()); Date date = new Date(); for (Item each : news.getItem()) { ContentValues weatherValues = new ContentValues(); try { date = simpleDateFormat.parse(each.getPubDate()); } catch (ParseException e) { Log.e(TAG, "e:" + e); } weatherValues.put(NewsColumns.DATE, date.getTime()); weatherValues.put(NewsColumns.TITLE, each.getTitle()); weatherValues.put(NewsColumns.DESCRIPTION, Html.toHtml(new SpannedString(each.getDescription()))); weatherValues.put(NewsColumns.URL, each.getLink()); weatherValues.put(NewsColumns.GUID, each.getGuid().getContent()); cVVector.add(weatherValues); } int inserted = 0; // add to database ContentResolver resolver = getContext().getContentResolver(); if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray); } // Set the date to day minus two to delete old data from the database date = new Date(); date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3); int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?", new String[] { String.valueOf(date.getTime()) }); } @Override public void onFailure(Call<Rss> call, Throwable t) { Log.e(TAG, "onFailure: " + t.toString()); } }); // TODO: 4/22/16 possible refactoring //checking the last update and notify if it' the first of the day SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate); long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS); if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context) * DateUtils.SECOND_IN_MILLIS) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); Date date = new Date(System.currentTimeMillis()); String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS), simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30), simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS), simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) }; String endTime = simpleDateFormat.format(date); int iterator = 1; while (iterator < CountColumns.ALL_COLUMNS.length) { final int round = iterator; App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime) .enqueue(new Callback<CountEarthquakes>() { @Override public void onResponse(Call<CountEarthquakes> call, Response<CountEarthquakes> response) { ContentValues count = new ContentValues(); count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount()); ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null, null); if (cursor != null) { if (cursor.getCount() < 1) { long inserted = ContentUris .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count)); //Log.d(TAG, "inserted:" + inserted); } else { int updated = contentResolver.update(CountColumns.CONTENT_URI, count, CountColumns._ID + " = ?", new String[] { "1" }); //Log.d(TAG, "updated: " + updated); } cursor.close(); } } @Override public void onFailure(Call<CountEarthquakes> call, Throwable t) { Log.e(TAG, "Error: " + t); } }); iterator++; } //refreshing last sync prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply(); } // notify PagerActivity that data has been updated context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false); context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false); context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false); updateWidgets(); }
From source file:com.dileepindia.cordova.sms.SMSPlugin.java
protected void createContentObserver() { Context ctx = this.cordova.getActivity(); this.mObserver = new ContentObserver(new Handler()) { public void onChange(boolean selfChange) { onChange(selfChange, null);/*from w w w.ja v a 2 s. co m*/ } public void onChange(boolean selfChange, Uri uri) { Log.d("SMSPlugin", "onChange, selfChange: " + selfChange + ", uri: " + uri); int id = -1; if (uri != null) { String str = uri.toString(); if (str.startsWith("content://sms/")) { String box_or_id = str.substring("content://sms/".length()); try { id = Integer.parseInt(str); Log.d("SMSPlugin", "sms id: " + id); } catch (NumberFormatException localNumberFormatException) { } } } if (id == -1) { uri = Uri.parse("content://sms/inbox"); } ContentResolver resolver = SMSPlugin.this.cordova.getActivity().getContentResolver(); Cursor cur = resolver.query(uri, null, null, null, "_id desc"); if (cur != null) { int n = cur.getCount(); Log.d("SMSPlugin", "n = " + n); if ((n > 0) && (cur.moveToFirst())) { JSONObject json = SMSPlugin.this.getJsonFromCursor(cur); if (json != null) { SMSPlugin.this.onSMSArrive(json); } else { Log.d("SMSPlugin", "fetch record return null"); } } cur.close(); } } }; ctx.getContentResolver().registerContentObserver(Uri.parse("content://sms/inbox"), true, this.mObserver); Log.d("SMSPlugin", "sms inbox observer registered"); }
From source file:com.nnm.smsviet.Message.java
/** * Fetch MMS parts./*from ww w .j av a 2 s . co m*/ * * @param context * {@link Context} */ private void fetchMmsParts(final Context context) { final ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?", new String[] { String.valueOf(this.id) }, null); if (cursor == null || !cursor.moveToFirst()) { return; } final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]); final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]); final int iText = cursor.getColumnIndex("text"); do { final int pid = cursor.getInt(iID); final String ct = cursor.getString(iCT); Log.d(TAG, "part: " + pid + " " + ct); // get part InputStream is = null; final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid); try { is = cr.openInputStream(uri); } catch (IOException e) { Log.e(TAG, "Failed to load part data", e); } if (is == null) { Log.i(TAG, "InputStream for part " + pid + " is null"); if (iText >= 0 && ct.startsWith("text/")) { this.body = cursor.getString(iText); } continue; } if (ct == null) { continue; } if (ct.startsWith("image/")) { this.picture = BitmapFactory.decodeStream(is); final Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(uri, ct); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); this.contentIntent = i; continue; // skip the rest } else if (ct.startsWith("video/") || ct.startsWith("audio/")) { this.picture = BITMAP_PLAY; final Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(uri, ct); this.contentIntent = i; continue; // skip the rest } else if (ct.startsWith("text/")) { this.body = this.fetchPart(is); } if (is != null) { try { is.close(); } catch (IOException e) { Log.e(TAG, "Failed to close stream", e); } // Ignore } } while (cursor.moveToNext()); }
From source file:com.murrayc.galaxyzoo.app.syncadapter.SyncAdapter.java
private boolean doUploadSync(final String itemId, final String subjectId, final String authName, final String authApiKey) throws ZooniverseClient.UploadException { //Note: I tried using HttpPost.getParams().setParameter() instead of the NameValuePairs, //but that did not allow multiple parameters with the same name, which we need. final List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair(PARAM_PART_CLASSIFICATION + "[subject_ids][]", subjectId)); final ContentResolver resolver = getContentResolver(); //Mark it as a favorite if necessary: {/*w ww . j a v a 2 s . c o m*/ final String[] projection = { Item.Columns.FAVORITE }; final Cursor c = resolver.query(Utils.getItemUri(itemId), projection, null, new String[] {}, null); if (c.moveToFirst()) { final int favorite = c.getInt(0); if (favorite == 1) { nameValuePairs.add(new BasicNameValuePair(PARAM_PART_CLASSIFICATION + "[favorite][]", "true")); } } c.close(); } final Cursor c; { final String selection = ClassificationAnswer.Columns.ITEM_ID + " = ?"; //We use ? to avoid SQL Injection. final String[] selectionArgs = { itemId }; final String orderBy = ClassificationAnswer.Columns.SEQUENCE + " ASC"; c = resolver.query(ClassificationAnswer.CONTENT_URI, PROJECTION_UPLOAD, selection, selectionArgs, orderBy); } int max_sequence = 0; while (c.moveToNext()) { final int sequence = c.getInt(0); final String questionId = c.getString(1); final String answerId = c.getString(2); //We could instead ORDER BY the sequence but that might be slightly slower and need a index. if (sequence > max_sequence) { max_sequence = sequence; } //Add the question's answer: //TODO: Is the string representation of sequence locale-dependent? final String questionKey = getAnnotationPart(sequence) + "[" + questionId + "]"; nameValuePairs.add(new BasicNameValuePair(questionKey, answerId)); final String selection = "(" + ClassificationCheckbox.Columns.ITEM_ID + " = ?) AND " + "(" + ClassificationCheckbox.Columns.QUESTION_ID + " == ?)"; //We use ? to avoid SQL Injection. final String[] selectionArgs = { itemId, questionId }; //Add the question's answer's selected checkboxes, if any: //The sequence will be the same for any selected checkbox for the same answer, //so we don't bother getting that, or sorting by that. final String[] projection = { ClassificationCheckbox.Columns.CHECKBOX_ID }; final String orderBy = ClassificationCheckbox.Columns.CHECKBOX_ID + " ASC"; final Cursor cursorCheckboxes = resolver.query(ClassificationCheckbox.CONTENT_URI, projection, selection, selectionArgs, orderBy); while (cursorCheckboxes.moveToNext()) { final String checkboxId = cursorCheckboxes.getString(0); //TODO: The Galaxy-Zoo server expects us to reuse the parameter name, //TODO: Is the string representation of sequence locale-dependent? nameValuePairs.add(new BasicNameValuePair(questionKey, checkboxId)); } cursorCheckboxes.close(); } c.close(); //Help the server know that the classification is from this Android app, //by reusing the User-Agent string as a parameter value. //See https://github.com/murraycu/android-galaxyzoo/issues/11 final String key = getAnnotationPart(max_sequence + 1) + "[user_agent]"; nameValuePairs.add(new BasicNameValuePair(key, HttpUtils.USER_AGENT_MURRAYC)); return mClient.uploadClassificationSync(authName, authApiKey, nameValuePairs); }
From source file:com.andrew.apollo.utils.MusicUtils.java
/** * @param context The {@link Context} to use. * @param name The name of the new playlist. * @return A new playlist ID./*from ww w . j a v a2s . c o m*/ */ public static long createPlaylist(final Context context, final String name) { long result = -1; if (name != null && name.length() > 0) { final ContentResolver resolver = context.getContentResolver(); final String[] projection = new String[] { PlaylistsColumns.NAME }; final String selection = PlaylistsColumns.NAME + " = ?"; Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, selection, new String[] { name }, null); if (cursor != null && cursor.getCount() <= 0) { final ContentValues values = new ContentValues(1); values.put(PlaylistsColumns.NAME, name); final Uri uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values); if (uri != null) { result = Long.parseLong(uri.getLastPathSegment()); } } if (cursor != null) { cursor.close(); } } return result; }
From source file:gov.wa.wsdot.android.wsdot.service.FerriesTerminalSailingSpaceSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/* w ww. j a v a2s .c o m*/ 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_terminal_sailing_space" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.SECOND_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(TERMINAL_SAILING_SPACE_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(); JSONArray array = new JSONArray(jsonFile); List<ContentValues> terminal = new ArrayList<ContentValues>(); int numItems = array.length(); for (int j = 0; j < numItems; j++) { JSONObject item = array.getJSONObject(j); ContentValues sailingSpaceValues = new ContentValues(); sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ID, item.getInt("TerminalID")); sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_NAME, item.getString("TerminalName")); sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ABBREV, item.getString("TerminalAbbrev")); sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES, item.getString("DepartingSpaces")); sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED, dateFormat.format(new Date(System.currentTimeMillis()))); if (starred.contains(item.getInt("TerminalID"))) { sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_IS_STARRED, 1); } terminal.add(sailingSpaceValues); } // Purge existing terminal sailing space items covered by incoming data resolver.delete(FerriesTerminalSailingSpace.CONTENT_URI, null, null); // Bulk insert all the new terminal sailing space items resolver.bulkInsert(FerriesTerminalSailingSpace.CONTENT_URI, terminal.toArray(new ContentValues[terminal.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_terminal_sailing_space" }); responseString = "OK"; } catch (Exception e) { Log.e(TAG, "Error: " + e.getMessage()); responseString = e.getMessage(); } } else { responseString = "NOP"; } Intent broadcastIntent = new Intent(); broadcastIntent .setAction("gov.wa.wsdot.android.wsdot.intent.action.FERRIES_TERMINAL_SAILING_SPACE_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:gov.wa.wsdot.android.wsdot.service.FerriesSchedulesSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/*from ww w. j a v a 2s . c o m*/ 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); }