List of usage examples for android.net Uri withAppendedPath
public static Uri withAppendedPath(Uri baseUri, String pathSegment)
From source file:fr.shywim.antoinedaniel.utils.Utils.java
public static boolean prepareDownloadFromCdn(Context context, String soundName, String imageName, String description, String link, int version, boolean force) throws IOException { String extImgPath = context.getExternalFilesDir(null) + "/img/"; String extSndPath = context.getExternalFilesDir(null) + "/snd/"; File sndDir = new File(context.getExternalFilesDir(null) + "/snd"); if (!sndDir.exists()) if (!sndDir.mkdirs()) return false; File imgDir = new File(context.getExternalFilesDir(null) + "/img"); if (!imgDir.exists()) if (!imgDir.mkdirs()) return false; File file = new File(extSndPath + soundName + ".ogg"); if (!downloadFileFromCdn(context, file, soundName, "snd/", ".ogg", force)) { //noinspection ResultOfMethodCallIgnored file.delete();//from www. jav a 2s. co m return false; } file = new File(extImgPath + imageName + ".jpg"); if (!downloadFileFromCdn(context, file, imageName, "img/", ".jpg", force)) { //noinspection ResultOfMethodCallIgnored file.delete(); return false; } Uri uri = Uri.withAppendedPath(ProviderConstants.SOUND_NAME_URI, soundName); ContentValues cv = new ContentValues(); cv.put(ProviderContract.SoundEntry.COLUMN_SOUND_NAME, soundName); cv.put(ProviderContract.SoundEntry.COLUMN_IMAGE_NAME, imageName); cv.put(ProviderContract.SoundEntry.COLUMN_DESC, description); cv.put(ProviderContract.SoundEntry.COLUMN_LINK, link); cv.put(ProviderContract.SoundEntry.COLUMN_NAME_VERSION, version); if (uri != null) { context.getContentResolver().update(uri, cv, null, null); return true; } else return false; }
From source file:com.android.dialer.calllog.ContactInfoHelper.java
/** * Determines the contact information for the given phone number. * <p>/* ww w . j a v a 2 s. c o m*/ * It returns the contact info if found. * <p> * If no contact corresponds to the given phone number, returns {@link ContactInfo#EMPTY}. * <p> * If the lookup fails for some other reason, it returns null. */ private ContactInfo queryContactInfoForPhoneNumber(String number, String countryIso) { if (TextUtils.isEmpty(number)) { return null; } String contactNumber = number; if (!TextUtils.isEmpty(countryIso)) { // Normalize the number: this is needed because the PhoneLookup query below does not // accept a country code as an input. String numberE164 = PhoneNumberUtils.formatNumberToE164(number, countryIso); if (!TextUtils.isEmpty(numberE164)) { // Only use it if the number could be formatted to E164. contactNumber = numberE164; } } // The "contactNumber" is a regular phone number, so use the PhoneLookup table. Uri uri = Uri.withAppendedPath(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, Uri.encode(contactNumber)); ContactInfo info = lookupContactFromUri(uri); if (info != null && info != ContactInfo.EMPTY) { info.formattedNumber = formatPhoneNumber(number, null, countryIso); } else if (mCachedNumberLookupService != null) { CachedContactInfo cacheInfo = mCachedNumberLookupService.lookupCachedContactFromNumber(mContext, number); if (cacheInfo != null) { info = cacheInfo.getContactInfo().isBadData ? null : cacheInfo.getContactInfo(); } else { info = null; } } return info; }
From source file:com.ultramegasoft.flavordex2.fragment.ViewFlavorsFragment.java
@SuppressWarnings("ConstantConditions") @NonNull/*from w w w .j a va 2s . co m*/ @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { final Context context = getContext(); if (context == null) { return null; } Uri uri; switch (id) { case LOADER_FLAVOR: uri = Uri.withAppendedPath(Tables.Entries.CONTENT_ID_URI_BASE, mEntryId + "/flavor"); return new CursorLoader(context, uri, null, null, null, Tables.EntriesFlavors.POS + " ASC"); case LOADER_DEFAULT_FLAVOR: case LOADER_RESET_FLAVOR: final Bundle args = getArguments(); final long catId = args != null ? args.getLong(ViewEntryFragment.ARG_ENTRY_CAT_ID) : 0; uri = Uri.withAppendedPath(Tables.Cats.CONTENT_ID_URI_BASE, catId + "/flavor"); return new CursorLoader(context, uri, null, null, null, Tables.Flavors.POS + " ASC"); } return null; }
From source file:com.example.android.lnotifications.OtherMetadataFragment.java
/** * Updates the Contact information on the screen when a contact is picked. * * @param contactUri The Uri from which the contact is retrieved. *//* w w w .j av a 2 s.co m*/ private void updateContactEntryFromUri(Uri contactUri) { Cursor cursor = getActivity().getContentResolver().query(contactUri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { int idx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); String name = cursor.getString(idx); idx = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID); String hasPhoto = cursor.getString(idx); Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); ImageView contactPhoto = (ImageView) getActivity().findViewById(R.id.contact_photo); if (hasPhoto != null) { contactPhoto.setImageURI(photoUri); } else { Drawable defaultContactDrawable = getActivity().getResources() .getDrawable(R.drawable.ic_contact_picture); contactPhoto.setImageDrawable(defaultContactDrawable); } TextView contactName = (TextView) getActivity().findViewById(R.id.contact_name); contactName.setText(name); getActivity().findViewById(R.id.contact_entry).setVisibility(View.VISIBLE); getActivity().findViewById(R.id.attach_person).setVisibility(View.GONE); getActivity().findViewById(R.id.click_to_change).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { findContact(); } }); Log.i(TAG, String.format("Contact updated. Name %s, PhotoUri %s", name, photoUri)); } }
From source file:com.hybris.mobile.lib.commerce.sync.CatalogSyncAdapter.java
/** * Sync a specific category// ww w . j a v a 2 s . c o m * * @param categoryId Unique Identifier for a specific Category of product * @param currentPage Page Number to be received in response * @param pageSize Amount of product per page * @throws InterruptedException */ private void syncCategory(final String categoryId, int currentPage, int pageSize) { Log.i(TAG, "Syncing the category " + categoryId + ", page " + currentPage + " and page size " + pageSize); QueryProducts queryProducts = new QueryProducts(); queryProducts.setIdCategory(categoryId); if (currentPage != 0) { queryProducts.setCurrentPage(currentPage); } if (pageSize != 0) { queryProducts.setPageSize(pageSize); } getProducts(queryProducts, false, null, new Callback() { @Override public void onProductsLoadedSuccess(List<DataSync> products, Long total) { Log.i(TAG, "Response received after syncing the category " + categoryId); List<String> listCategory = new ArrayList<>(); listCategory.add(categoryId); // Saving all the products if (products != null && !products.isEmpty()) { for (DataSync product : products) { saveProduct(product, listCategory, false); } } // Update the sync status for the category ContentValues contentValues = new ContentValues(); contentValues.put(CatalogContract.DataBaseSyncStatusGroup.ATT_GROUP_ID, categoryId); contentValues.put(CatalogContract.DataBaseSyncStatusGroup.ATT_STATUS, SyncStatus.UPTODATE.getValue()); getContext().getContentResolver().update( Uri.withAppendedPath(CatalogContract.Provider.getUriSyncGroup(AUTHORITY), categoryId), contentValues, null, null); // Notify the content provider Uri uriToNotify = Uri.withAppendedPath(CatalogContract.Provider.getUriGroup(AUTHORITY), categoryId); Log.i(TAG, "Notify category changes for " + uriToNotify); getContext().getContentResolver().notifyChange(uriToNotify, null); } @Override public void onProductsLoadedError() { } }); }
From source file:ca.rmen.android.scrumchatter.team.Teams.java
/** * Query the teams table, and return a list of all teams, and the current team. *///from w w w .j a v a 2s. co m public Single<TeamsData> getAllTeams() { Log.v(TAG, "getAllTeams"); return Single.fromCallable(() -> { Log.v(TAG, "getAllTeams work"); List<Team> teams = new ArrayList<>(); Cursor c = mActivity.getContentResolver().query(TeamColumns.CONTENT_URI, new String[] { TeamColumns._ID, TeamColumns.TEAM_NAME }, null, null, TeamColumns.TEAM_NAME + " COLLATE NOCASE"); if (c != null) { try { // Add the names of all the teams while (c.moveToNext()) { int teamId = c.getInt(0); String teamName = c.getString(1); Uri teamUri = Uri.withAppendedPath(TeamColumns.CONTENT_URI, String.valueOf(teamId)); teams.add(new Team(teamUri, teamName)); } } finally { c.close(); } } return new TeamsData(getCurrentTeam(), teams); }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); }
From source file:com.jaspersoft.android.jaspermobile.activities.profile.fragment.ServersFragment.java
@Override public void onPositiveButtonClicked(int position) { Cursor cursor = mAdapter.getCursor(); cursor.moveToPosition(position);/*w w w . j a v a 2s . c om*/ long id = cursor.getLong(cursor.getColumnIndex(ServerProfilesTable._ID)); if (mServerProfileId == id) { Toast.makeText(getActivity(), "Can`t delete active profile", Toast.LENGTH_SHORT).show(); return; } Uri uri = Uri.withAppendedPath(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI, String.valueOf(id)); int deleteCount = getActivity().getContentResolver().delete(uri, null, null); if (deleteCount > 0) { Toast.makeText(getActivity(), R.string.spm_profile_deleted_toast, Toast.LENGTH_SHORT).show(); } mAdapter.finishActionMode(); }
From source file:edu.mit.mobile.android.locast.data.TaggableItem.java
/** * @param baseUri//w w w .j a va 2 s . c o m * @return the URI of the list of all tags for the given item */ public static Uri getTagListUri(Uri baseUri) { return Uri.withAppendedPath(baseUri, Tag.PATH); }
From source file:org.pixmob.droidlink.sync.SyncAdapter.java
private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider, SyncResult syncResult, boolean fullSync) { // Prepare the query. final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?"; final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE), String.valueOf(EventsContract.PENDING_DELETE_STATE) }; // Get local data to sync. final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8); final Set<String> eventsToDelete = new HashSet<String>(4); Cursor c = null;//from www .j a v a 2 s . c o m try { c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null); final int idIdx = c.getColumnIndexOrThrow(_ID); final int typeIdx = c.getColumnIndexOrThrow(TYPE); final int createdIdx = c.getColumnIndexOrThrow(CREATED); final int numberIdx = c.getColumnIndexOrThrow(NUMBER); final int nameIdx = c.getColumnIndexOrThrow(NAME); final int messageIdx = c.getColumnIndexOrThrow(MESSAGE); final int stateIdx = c.getColumnIndexOrThrow(STATE); while (c.moveToNext()) { final String eventId = c.getString(idIdx); final int eventState = c.getInt(stateIdx); if (EventsContract.PENDING_UPLOAD_STATE == eventState) { // This is a newly created event. final JSONObject event = new JSONObject(); try { event.put("deviceId", client.getDeviceId()); event.put("created", c.getLong(createdIdx)); event.put("type", c.getInt(typeIdx)); event.put("number", c.getString(numberIdx)); event.put("name", c.getString(nameIdx)); event.put("message", c.getString(messageIdx)); } catch (JSONException e) { Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e); syncResult.stats.numSkippedEntries++; continue; } eventsToUpload.put(eventId, event); } else if (EventsContract.PENDING_DELETE_STATE == eventState) { // The user wants this event to be deleted. eventsToDelete.add(eventId); } } } catch (RemoteException e) { Log.e(TAG, "Failed to get events: cannot sync", e); syncResult.stats.numIoExceptions++; } finally { if (c != null) { c.close(); c = null; } } final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32); final ContentValues values = new ContentValues(8); if (eventsToDelete.isEmpty()) { Log.i(TAG, "No events to delete"); } else { Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete"); } // Delete events on the remote server. for (final String eventId : eventsToDelete) { if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event: " + eventId); } try { client.delete("/events/" + eventId); if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event in local database: " + eventId); } batch.add(ContentProviderOperation .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build()); syncResult.stats.numDeletes++; } catch (IOException e) { Log.e(TAG, "Event deletion error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } } try { provider.applyBatch(batch); } catch (Exception e) { Log.w(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); if (fullSync) { // Get all events from the remote server. final JSONArray events; if (DEVELOPER_MODE) { Log.d(TAG, "Fetching events from the remote server"); } try { events = client.getAsArray("/events"); } catch (IOException e) { Log.e(TAG, "Event listing error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } final int eventsLen = events != null ? events.length() : 0; if (eventsLen == 0) { Log.i(TAG, "No events from the remote server"); } else { Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server"); } // Build a collection with local event identifiers. // This collection will be used to identify which events have // been deleted on the remote server. final Set<String> localEventIds; try { c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?", new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null); localEventIds = new HashSet<String>(c.getCount()); final int idIdx = c.getColumnIndexOrThrow(_ID); while (c.moveToNext()) { final String eventId = c.getString(idIdx); localEventIds.add(eventId); } } catch (RemoteException e) { Log.e(TAG, "Failed to get events from local database", e); syncResult.stats.numIoExceptions++; return; } finally { if (c != null) { c.close(); c = null; } } String newEventId = null; int newEventCount = 0; // Reconcile remote events with local events. for (int i = 0; i < eventsLen; ++i) { String eventId = null; try { final JSONObject event = events.getJSONObject(i); eventId = event.getString("id"); // Check if this event exists in the local database. if (localEventIds.contains(eventId)) { // Found the event: update it. values.clear(); values.put(NUMBER, trimToNull(event.getString("number"))); values.put(NAME, trimToNull(event.getString("name"))); values.put(MESSAGE, trimToNull(event.getString("message"))); if (DEVELOPER_MODE) { Log.d(TAG, "Updating event in local database: " + eventId); } batch.add(ContentProviderOperation .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)) .withExpectedCount(1).withValues(values).build()); syncResult.stats.numUpdates++; } else { // The event was not found: insert it. values.clear(); values.put(_ID, eventId); values.put(DEVICE_ID, event.getString("deviceId")); values.put(CREATED, event.getLong("created")); values.put(TYPE, event.getInt("type")); values.put(NUMBER, trimToNull(event.getString("number"))); values.put(NAME, trimToNull(event.getString("name"))); values.put(MESSAGE, trimToNull(event.getString("message"))); values.put(STATE, EventsContract.UPLOADED_STATE); if (DEVELOPER_MODE) { Log.d(TAG, "Adding event to local database: " + eventId); } batch.add(ContentProviderOperation .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)) .withValues(values).build()); syncResult.stats.numInserts++; ++newEventCount; if (newEventId == null) { newEventId = eventId; } } // This event now exists in the local database: // remove its identifier from this collection as we // don't want to delete it. localEventIds.remove(eventId); } catch (JSONException e) { Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e); syncResult.stats.numSkippedEntries++; continue; } } // The remaining event identifiers was removed on the remote // server: there are still present in the local database. These // events are now being deleted. for (final String eventId : localEventIds) { if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event in local database: " + eventId); } batch.add(ContentProviderOperation .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build()); syncResult.stats.numDeletes++; } try { provider.applyBatch(batch); } catch (Exception e) { Log.e(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); if (newEventCount > 1) { newEventId = null; } if (newEventCount != 0) { startSyncNotificationService(newEventCount, newEventId); } } final int numEventsToUpload = eventsToUpload.size(); if (numEventsToUpload == 0) { Log.i(TAG, "No events to upload"); } else { Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload"); } // Send local events to the remote server. for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) { final String eventId = entry.getKey(); if (DEVELOPER_MODE) { Log.d(TAG, "Uploading event: " + eventId); } final JSONObject event = entry.getValue(); try { client.put("/events/" + eventId, event); if (DEVELOPER_MODE) { Log.d(TAG, "Updating event state to UPLOADED: " + eventId); } values.clear(); values.put(STATE, EventsContract.UPLOADED_STATE); batch.add(ContentProviderOperation .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values) .withExpectedCount(1).build()); syncResult.stats.numUpdates++; Log.i(TAG, "Event upload successful: " + eventId); } catch (NetworkClientException e) { if (e.getStatusCode() == 404) { Log.e(TAG, "Device not found: cannot sync", e); registerDevice(); } else { Log.e(TAG, "Network error: cannot sync", e); } syncResult.stats.numIoExceptions++; return; } catch (IOException e) { Log.e(TAG, "Event upload error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } } try { provider.applyBatch(batch); } catch (Exception e) { Log.w(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); final SharedPreferences.Editor prefsEditor = prefs.edit(); final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty(); if (syncRequired) { // Generate an unique sync token: the server will send this token to // every devices. If this token is received on this device, the sync // will not start. final String syncToken = UUID.randomUUID().toString(); prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken); Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // Sync user devices. try { final JSONObject data = new JSONObject(); data.put("token", syncToken); client.post("/devices/" + client.getDeviceId() + "/sync", data); } catch (NetworkClientException e) { if (e.getStatusCode() == 404) { registerDevice(); } } catch (IOException e) { Log.e(TAG, "Device sync error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } catch (JSONException e) { Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e); syncResult.stats.numIoExceptions++; return; } } // Store sync time. prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis()); Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); }
From source file:com.shafiq.myfeedle.core.StatusDialog.java
private void showDialog() { if (mService == SMS) { // if mRect go straight to message app... if (mRect != null) QuickContact.showQuickContact(this, mRect, Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, mEsid), QuickContact.MODE_LARGE, null); else {/*w ww .j a v a 2 s. co m*/ startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mEsid))); finish(); } } else if (mService == RSS) { if (mEsid != null) { startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(mEsid))); finish(); } else { (Toast.makeText(StatusDialog.this, "RSS item has no link", Toast.LENGTH_LONG)).show(); finish(); } } else if (items != null) { // offer options for Comment, Post, Settings and Refresh // loading the likes/retweet and other options takes too long, so load them in the MyfeedleCreatePost.class mDialog = (new AlertDialog.Builder(this)).setItems(items, this).setCancelable(true) .setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface arg0) { finish(); } }).create(); mDialog.show(); } else { if (mAppWidgetId != Myfeedle.INVALID_ACCOUNT_ID) { // informational messages go to settings mFinish = true; startActivity(Myfeedle.getPackageIntent(this, ManageAccounts.class) .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId)); finish(); } else { (Toast.makeText(StatusDialog.this, R.string.widget_loading, Toast.LENGTH_LONG)).show(); // force widgets rebuild startService(Myfeedle.getPackageIntent(this, MyfeedleService.class).setAction(ACTION_REFRESH)); finish(); } } }