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.brightsilence.dev.androidphotobackup.PhotoBackupService.java
/** Method to examine media stores on both internal and external storage and backup the files (via the handleFiles method) *//* w ww . j a va2s . c o m*/ private void backupContent() { ContentResolver contentResolver = getContentResolver(); for (int i = 0; i < 2; i++) { Uri src; if (i == 0) { src = MediaStore.Images.Media.INTERNAL_CONTENT_URI; Log.d(TAG, "Examining internal media storage\n"); } else { src = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; Log.d(TAG, "Examining external media storage\n"); } Cursor cursor = contentResolver.query(src, null, null, null, null); if (cursor.moveToFirst()) { mExistingDirs = new HashSet<String>(); handleFiles(cursor); } Log.d(TAG, "Finished storage examination"); cursor.close(); } }
From source file:com.polyvi.xface.extension.XMessagingExt.java
/** * ?//from w ww .ja va2 s .co m * @param comparisonMsg ?? * @param folderType * @param startIndex * @param endIndex ? * @return ? */ private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex) throws JSONException { // TODO:???Email? if (null == folderType) {// folderTypenull? folderType = FOLDERTYPE_DRAFT; } ArrayList<String> projections = new ArrayList<String>(); projections.add("_id"); projections.add("subject"); projections.add("address"); projections.add("body"); ArrayList<String> projectionsValue = new ArrayList<String>(); projectionsValue.add(comparisonMsg.optString("messageId")); projectionsValue.add(comparisonMsg.optString("subject")); projectionsValue.add(comparisonMsg.optString("destinationAddresses")); projectionsValue.add(comparisonMsg.optString("body")); StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue); int isRead = comparisonMsg.getInt("isRead"); if (-1 != isRead) { if (null == selection) { selection = new StringBuilder(); } else { selection.append(" AND "); } selection.append("read"); selection.append("="); selection.append(isRead); } String selectionStr = null; if (null != selection) { selectionStr = selection.toString(); } folderType = folderType.toLowerCase(); Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType); JSONArray messages = new JSONArray(); try { ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = resolver.query(findUri, null, selectionStr, null, null); if (null == cursor) { return messages; } int count = endIndex - startIndex + 1; if (cursor.moveToPosition(startIndex)) { do { JSONObject message = getMessageFromCursor(cursor); messages.put(message); count--; } while (cursor.moveToNext() && count > 0); } cursor.close(); } catch (SQLiteException ex) { ex.printStackTrace(); } return messages; }
From source file:com.akop.bach.fragment.xboxlive.AchievementsFragment.java
@Override protected Cursor getIconCursor() { if (getActivity() == null) return null; ContentResolver cr = getActivity().getContentResolver(); return cr.query(Achievements.CONTENT_URI, new String[] { Achievements._ID, Achievements.ICON_URL }, Achievements.GAME_ID + "=" + mTitleId, null, Achievements.DEFAULT_SORT_ORDER); }
From source file:com.granita.contacticloudsync.syncadapter.AccountSettings.java
@SuppressWarnings("Recycle") private void update_0_1() throws URISyntaxException { String v0_principalURL = accountManager.getUserData(account, "principal_url"), v0_addressBookPath = accountManager.getUserData(account, "addressbook_path"); Constants.log.debug("Old principal URL = " + v0_principalURL); Constants.log.debug("Old address book path = " + v0_addressBookPath); URI principalURI = new URI(v0_principalURL); // update address book if (v0_addressBookPath != null) { String addressBookURL = principalURI.resolve(v0_addressBookPath).toASCIIString(); Constants.log.debug("New address book URL = " + addressBookURL); accountManager.setUserData(account, "addressbook_url", addressBookURL); }// ww w.jav a 2 s . c om // update calendars ContentResolver resolver = context.getContentResolver(); Uri calendars = Calendars.CONTENT_URI.buildUpon().appendQueryParameter(Calendars.ACCOUNT_NAME, account.name) .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type) .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true").build(); @Cleanup Cursor cursor = resolver.query(calendars, new String[] { Calendars._ID, Calendars.NAME }, null, null, null); while (cursor != null && cursor.moveToNext()) { int id = cursor.getInt(0); String v0_path = cursor.getString(1), v1_url = principalURI.resolve(v0_path).toASCIIString(); Constants.log.debug("Updating calendar #" + id + " name: " + v0_path + " -> " + v1_url); Uri calendar = ContentUris.appendId( Calendars.CONTENT_URI.buildUpon().appendQueryParameter(Calendars.ACCOUNT_NAME, account.name) .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type) .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true"), id).build(); ContentValues newValues = new ContentValues(1); newValues.put(Calendars.NAME, v1_url); if (resolver.update(calendar, newValues, null, null) != 1) Constants.log.debug("Number of modified calendars != 1"); } accountManager.setUserData(account, "principal_url", null); accountManager.setUserData(account, "addressbook_path", null); accountManager.setUserData(account, KEY_SETTINGS_VERSION, "1"); }
From source file:gov.wa.wsdot.android.wsdot.service.BorderWaitSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/* www .j a 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, new String[] { Caches.CACHE_LAST_UPDATED }, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "border_wait" }, 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) > (15 * 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(BORDER_WAIT_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("waittimes"); 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(BorderWait.BORDER_WAIT_ID, item.getInt("id")); timesValues.put(BorderWait.BORDER_WAIT_TITLE, item.getString("name")); timesValues.put(BorderWait.BORDER_WAIT_UPDATED, item.getString("updated")); timesValues.put(BorderWait.BORDER_WAIT_LANE, item.getString("lane")); timesValues.put(BorderWait.BORDER_WAIT_ROUTE, item.getInt("route")); timesValues.put(BorderWait.BORDER_WAIT_DIRECTION, item.getString("direction")); timesValues.put(BorderWait.BORDER_WAIT_TIME, item.getInt("wait")); if (starred.contains(item.getInt("id"))) { timesValues.put(BorderWait.BORDER_WAIT_IS_STARRED, 1); } times.add(timesValues); } // Purge existing border wait times covered by incoming data resolver.delete(BorderWait.CONTENT_URI, null, null); // Bulk insert all the new travel times resolver.bulkInsert(BorderWait.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[] { "border_wait" }); 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.BORDER_WAIT_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:com.frostwire.android.gui.Librarian.java
private void syncMediaStore(final Context context, byte fileType, Set<File> ignorableFiles) { TableFetcher fetcher = TableFetchers.getFetcher(fileType); if (fetcher == null) { return;/*from www. j a v a2 s . c om*/ } Cursor c = null; try { ContentResolver cr = context.getContentResolver(); String where = MediaColumns.DATA + " LIKE ?"; String[] whereArgs = new String[] { Platforms.data() + "%" }; c = cr.query(fetcher.getContentUri(), new String[] { MediaColumns._ID, MediaColumns.DATA }, where, whereArgs, null); if (c == null) { return; } int idCol = c.getColumnIndex(MediaColumns._ID); int pathCol = c.getColumnIndex(MediaColumns.DATA); List<Integer> ids = new ArrayList<>(0); while (c.moveToNext()) { int id = Integer.valueOf(c.getString(idCol)); String path = c.getString(pathCol); if (ignorableFiles.contains(new File(path))) { ids.add(id); } } cr.delete(fetcher.getContentUri(), MediaColumns._ID + " IN " + buildSet(ids), null); } catch (Throwable e) { Log.e(TAG, "General failure during sync of MediaStore", e); } finally { if (c != null) { c.close(); } } }
From source file:gov.wa.wsdot.android.wsdot.service.TravelTimesSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/* ww w . j av a 2s . co 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, 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:gov.wa.wsdot.android.wsdot.service.CamerasSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;//from w w w . j a va2 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:com.android.calendar.Event.java
/** * Performs a query to return all visible instances in the given range * that match the given selection. This is a blocking function and * should not be done on the UI thread. This will cause an expansion of * recurring events to fill this time range if they are not already * expanded and will slow down for larger time ranges with many * recurring events./*w w w .j ava2s .co m*/ * * @param cr The ContentResolver to use for the query * @param projection The columns to return * @param begin The start of the time range to query in UTC millis since * epoch * @param end The end of the time range to query in UTC millis since * epoch * @param selection Filter on the query as an SQL WHERE statement * @param selectionArgs Args to replace any '?'s in the selection * @param orderBy How to order the rows as an SQL ORDER BY statement * @return A Cursor of instances matching the selection */ private static final Cursor instancesQuery(ContentResolver cr, String[] projection, int startDay, int endDay, String selection, String[] selectionArgs, String orderBy) { String WHERE_CALENDARS_SELECTED = Calendars.VISIBLE + "=?"; String[] WHERE_CALENDARS_ARGS = { "1" }; String DEFAULT_SORT_ORDER = "begin ASC"; Uri.Builder builder = Instances.CONTENT_BY_DAY_URI.buildUpon(); ContentUris.appendId(builder, startDay); ContentUris.appendId(builder, endDay); if (TextUtils.isEmpty(selection)) { selection = WHERE_CALENDARS_SELECTED; selectionArgs = WHERE_CALENDARS_ARGS; } else { selection = "(" + selection + ") AND " + WHERE_CALENDARS_SELECTED; if (selectionArgs != null && selectionArgs.length > 0) { selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); selectionArgs[selectionArgs.length - 1] = WHERE_CALENDARS_ARGS[0]; } else { selectionArgs = WHERE_CALENDARS_ARGS; } } return cr.query(builder.build(), projection, selection, selectionArgs, orderBy == null ? DEFAULT_SORT_ORDER : orderBy); }
From source file:com.akop.bach.fragment.playstation.TrophiesFragment.java
private void loadGameDetails() { View view = getView();//from w ww . ja va2 s . co 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()) { int platinum = c.getInt(GamesFragment.COLUMN_UNLOCKED_PLATINUM); int gold = c.getInt(GamesFragment.COLUMN_UNLOCKED_GOLD); int silver = c.getInt(GamesFragment.COLUMN_UNLOCKED_SILVER); int bronze = c.getInt(GamesFragment.COLUMN_UNLOCKED_BRONZE); int progress = c.getInt(GamesFragment.COLUMN_PROGRESS); TextView tv; ImageView iv; ProgressBar pb; if ((tv = (TextView) view.findViewById(R.id.game_title)) != null) tv.setText(c.getString(GamesFragment.COLUMN_TITLE)); if ((tv = (TextView) view.findViewById(R.id.game_progress_ind)) != null) tv.setText(progress + ""); if ((pb = (ProgressBar) view.findViewById(R.id.game_progress_bar)) != null) pb.setProgress(progress); if ((tv = (TextView) view.findViewById(R.id.game_trophies_platinum)) != null) tv.setText(platinum + ""); if ((tv = (TextView) view.findViewById(R.id.game_trophies_gold)) != null) tv.setText(gold + ""); if ((tv = (TextView) view.findViewById(R.id.game_trophies_silver)) != null) tv.setText(silver + ""); if ((tv = (TextView) view.findViewById(R.id.game_trophies_bronze)) != null) tv.setText(bronze + ""); if ((tv = (TextView) view.findViewById(R.id.game_trophies_all)) != null) tv.setText((platinum + gold + silver + bronze) + ""); ImageCache ic = ImageCache.getInstance(); String iconUrl = c.getString(GamesFragment.COLUMN_ICON_URL); Bitmap bmp; if ((bmp = ic.getCachedBitmap(iconUrl, mCp)) != 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, mCp); } } } } finally { c.close(); } } }