List of usage examples for android.net Uri getLastPathSegment
@Nullable public abstract String getLastPathSegment();
From source file:br.com.bioscada.apps.biotracks.services.TrackRecordingService.java
/** * Inserts a waypoint.//ww w . ja v a 2 s .c o m * * @param waypointCreationRequest the waypoint creation request * @return the waypoint id */ public long insertWaypoint(WaypointCreationRequest waypointCreationRequest) { if (!isRecording() || isPaused()) { return -1L; } Waypoint.WaypointType waypointType = waypointCreationRequest.getType(); boolean isStatistics = waypointType == Waypoint.WaypointType.STATISTICS; // Get name String name; if (waypointCreationRequest.getName() != null) { name = waypointCreationRequest.getName(); } else { int nextWaypointNumber = myTracksProviderUtils.getNextWaypointNumber(recordingTrackId, waypointType); if (nextWaypointNumber == -1) { nextWaypointNumber = 0; } name = getString(isStatistics ? R.string.marker_split_name_format : R.string.marker_name_format, nextWaypointNumber); } // Get category String category = waypointCreationRequest.getCategory() != null ? waypointCreationRequest.getCategory() : ""; // Get tripStatistics, description, and icon TripStatistics tripStatistics; String description; String icon; if (isStatistics) { long now = System.currentTimeMillis(); markerTripStatisticsUpdater.updateTime(now); tripStatistics = markerTripStatisticsUpdater.getTripStatistics(); markerTripStatisticsUpdater = new TripStatisticsUpdater(now); description = new DescriptionGeneratorImpl(this).generateWaypointDescription(tripStatistics); icon = getString(R.string.marker_statistics_icon_url); } else { tripStatistics = null; description = waypointCreationRequest.getDescription() != null ? waypointCreationRequest.getDescription() : ""; icon = getString(R.string.marker_waypoint_icon_url); } // Get length and duration double length; long duration; Location location = getLastValidTrackPointInCurrentSegment(recordingTrackId); if (location != null && trackTripStatisticsUpdater != null) { TripStatistics stats = trackTripStatisticsUpdater.getTripStatistics(); length = stats.getTotalDistance(); duration = stats.getTotalTime(); } else { if (!waypointCreationRequest.isTrackStatistics()) { return -1L; } // For track statistics, make it an impossible location location = new Location(""); location.setLatitude(100); location.setLongitude(180); length = 0.0; duration = 0L; } String photoUrl = waypointCreationRequest.getPhotoUrl() != null ? waypointCreationRequest.getPhotoUrl() : ""; // Insert waypoint Waypoint waypoint = new Waypoint(name, description, category, icon, recordingTrackId, waypointType, length, duration, -1L, -1L, location, tripStatistics, photoUrl); if (isStatistics) lastSplitWaypoint = waypoint; Uri uri = myTracksProviderUtils.insertWaypoint(waypoint); return Long.parseLong(uri.getLastPathSegment()); }
From source file:com.android.calendar.AllInOneActivity.java
private void initFragments(long timeMillis, int viewType, Bundle icicle) { if (DEBUG) {// www .j a v a 2s. co m Log.d(TAG, "Initializing to " + timeMillis + " for view " + viewType); } FragmentTransaction ft = getFragmentManager().beginTransaction(); if (mShowCalendarControls) { Fragment miniMonthFrag = new MonthByWeekFragment(timeMillis, true); ft.replace(R.id.mini_month, miniMonthFrag); mController.registerEventHandler(R.id.mini_month, (EventHandler) miniMonthFrag); Fragment selectCalendarsFrag = new SelectVisibleCalendarsFragment(); ft.replace(R.id.calendar_list, selectCalendarsFrag); mController.registerEventHandler(R.id.calendar_list, (EventHandler) selectCalendarsFrag); } if (!mShowCalendarControls || viewType == ViewType.EDIT) { mMiniMonth.setVisibility(View.GONE); mCalendarsList.setVisibility(View.GONE); } EventInfo info = null; if (viewType == ViewType.EDIT) { mPreviousView = GeneralPreferences.getSharedPreferences(this).getInt(GeneralPreferences.KEY_START_VIEW, GeneralPreferences.DEFAULT_START_VIEW); long eventId = -1; Intent intent = getIntent(); Uri data = intent.getData(); if (data != null) { try { eventId = Long.parseLong(data.getLastPathSegment()); } catch (NumberFormatException e) { if (DEBUG) { Log.d(TAG, "Create new event"); } } } else if (icicle != null && icicle.containsKey(BUNDLE_KEY_EVENT_ID)) { eventId = icicle.getLong(BUNDLE_KEY_EVENT_ID); } long begin = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1); long end = intent.getLongExtra(EXTRA_EVENT_END_TIME, -1); info = new EventInfo(); if (end != -1) { info.endTime = new Time(); info.endTime.set(end); } if (begin != -1) { info.startTime = new Time(); info.startTime.set(begin); } info.id = eventId; // We set the viewtype so if the user presses back when they are // done editing the controller knows we were in the Edit Event // screen. Likewise for eventId mController.setViewType(viewType); mController.setEventId(eventId); } else { mPreviousView = viewType; } setMainPane(ft, R.id.main_pane, viewType, timeMillis, true); ft.commit(); // this needs to be after setMainPane() Time t = new Time(mTimeZone); t.set(timeMillis); if (viewType == ViewType.AGENDA && icicle != null) { mController.sendEvent(this, EventType.GO_TO, t, null, icicle.getLong(BUNDLE_KEY_EVENT_ID, -1), viewType); } else if (viewType != ViewType.EDIT) { mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType); } }
From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java
private void restoreMap() { Uri data = this.getIntent().getData(); if (mTrackId > -1) { // 1st method: track from a previous instance of this moveToTrack(mTrackId, false);// ww w .j a v a 2 s . com } else if (getIntent().getData() != null) { // 2nd method: track ordered to make long loadTrackId = Long.parseLong(data.getLastPathSegment()); mAverageSpeed = 0.0; moveToTrack(loadTrackId, true); } else { // 3rd method: just try the last track moveToLastTrack(); } }
From source file:com.android.music.TrackBrowserFragment.java
@Override public void startActivityForResult(Intent intent, int requestCode) { // TODO Auto-generated method stub switch (requestCode) { case SCAN_DONE: if (requestCode == getActivity().RESULT_CANCELED) { getActivity().finish();//ww w . j a v a 2 s. c om } else { getTrackCursor(mAdapter.getQueryHandler(), null, true); } break; case NEW_PLAYLIST: if (requestCode == getActivity().RESULT_OK) { Uri uri = intent.getData(); if (uri != null) { long[] list = new long[] { mSelectedId }; MusicUtils.addToPlaylist(getActivity(), list, Integer.valueOf(uri.getLastPathSegment())); } } break; case SAVE_AS_PLAYLIST: if (requestCode == getActivity().RESULT_OK) { Uri uri = intent.getData(); if (uri != null) { long[] list = MusicUtils.getSongListForCursor(mTrackCursor); int plid = Integer.parseInt(uri.getLastPathSegment()); MusicUtils.addToPlaylist(getActivity(), list, plid); } } break; } }
From source file:com.ziyou.selftravel.download.DownloadManager.java
/** * Enqueue a new download. The download will start automatically once the * download manager is ready to execute it and connectivity is available. * //w ww . j av a 2 s. co m * @param request the parameters specifying this download * @return an ID for the download, unique across the system. This ID is used * to make future calls related to this download. */ public long enqueue(Request request) { ContentValues values = request.toContentValues(mPackageName); Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values); long id = Long.parseLong(downloadUri.getLastPathSegment()); return id; }
From source file:Main.java
/** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders./*from w ww .jav a2 s .c om*/ * * @param context The context. * @param uri The Uri to query. */ public static String getPath(final Context context, final Uri uri) { // DocumentProvider if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT // is Kitkat or later && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } // DriveDocument else if (isDriveDocument(uri)) { // I have not found a way to generate the absolute url. // Check from outside if it's a GoogleDrive document. // Generate a bitmap and convert to bytes. return null; } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; }
From source file:com.android.contacts.common.model.ContactLoader.java
@Override public Contact loadInBackground() { try {/*from w ww .j ava2 s . c om*/ final ContentResolver resolver = getContext().getContentResolver(); final Uri uriCurrentFormat = ContactLoaderUtils.ensureIsContactUri(resolver, mLookupUri); final Contact cachedResult = sCachedResult; sCachedResult = null; // Is this the same Uri as what we had before already? In that case, reuse that result final Contact result; final boolean resultIsCached; if (cachedResult != null && UriUtils.areEqual(cachedResult.getLookupUri(), mLookupUri)) { // We are using a cached result from earlier. Below, we should make sure // we are not doing any more network or disc accesses result = new Contact(mRequestedUri, cachedResult); resultIsCached = true; } else { if (uriCurrentFormat.getLastPathSegment().equals(Constants.LOOKUP_URI_ENCODED)) { result = loadEncodedContactEntity(uriCurrentFormat, mLookupUri); } else { result = loadContactEntity(resolver, uriCurrentFormat); } resultIsCached = false; } if (result.isLoaded()) { if (result.isDirectoryEntry()) { if (!resultIsCached) { loadDirectoryMetaData(result); } } else if (mLoadGroupMetaData) { if (result.getGroupMetaData() == null) { loadGroupMetaData(result); } } if (mComputeFormattedPhoneNumber) { computeFormattedPhoneNumbers(result); } if (!resultIsCached) loadPhotoBinaryData(result); // Note ME profile should never have "Add connection" if (mLoadInvitableAccountTypes && result.getInvitableAccountTypes() == null) { loadInvitableAccountTypes(result); } } return result; } catch (Exception e) { Log.e(TAG, "Error loading the contact: " + mLookupUri, e); return Contact.forError(mRequestedUri, e); } }
From source file:com.android.calendar.AllInOneActivity.java
private long parseViewAction(final Intent intent) { long timeMillis = -1; Uri data = intent.getData(); if (data != null && data.isHierarchical()) { List<String> path = data.getPathSegments(); if (path.size() == 2 && path.get(0).equals("events")) { try { mViewEventId = Long.valueOf(data.getLastPathSegment()); if (mViewEventId != -1) { mIntentEventStartMillis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, 0); mIntentEventEndMillis = intent.getLongExtra(EXTRA_EVENT_END_TIME, 0); mIntentAttendeeResponse = intent.getIntExtra(ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE); mIntentAllDay = intent.getBooleanExtra(EXTRA_EVENT_ALL_DAY, false); timeMillis = mIntentEventStartMillis; }// w ww.ja v a 2 s . com } catch (NumberFormatException e) { // Ignore if mViewEventId can't be parsed } } } return timeMillis; }
From source file:com.google.android.dialer.provider.DialerProvider.java
@Override public Cursor query(Uri uri, final String[] projection, String selection, String[] selectionArgs, String sortOrder) {//from w ww. j a v a2 s . c om if (Log.isLoggable("DialerProvider", 2)) { Log.v("DialerProvider", "query: " + uri); } switch (sURIMatcher.match(uri)) { case 0: Context context = getContext(); if (!GoogleLocationSettingHelper.isGoogleLocationServicesEnabled(context) || !GoogleLocationSettingHelper.isSystemLocationSettingEnabled(context)) { if (Log.isLoggable("DialerProvider", Log.VERBOSE)) { Log.v("DialerProvider", "Location settings is disabled, ignoring query."); } return null; } final Location lastLocation = getLastLocation(); if (lastLocation == null) { if (Log.isLoggable("DialerProvider", Log.VERBOSE)) { Log.v("DialerProvider", "No location available, ignoring query."); } return null; } final String filter = Uri.encode(uri.getLastPathSegment()); String limit = uri.getQueryParameter("limit"); try { final int limitInt; if (limit == null) { limitInt = -1; } else { limitInt = Integer.parseInt(limit); } return execute(new Callable<Cursor>() { @Override public Cursor call() { return handleFilter(projection, filter, limitInt, lastLocation); } }, "FilterThread", 10000L, TimeUnit.MILLISECONDS); } catch (NumberFormatException e) { Log.e("DialerProvider", "query: invalid limit parameter: '" + limit + "'"); } break; } // TODO: Is this acceptable? return null; }
From source file:com.stockita.stockitapointofsales.activities.MainActivity.java
/** * Helper method to save and upload images to the server *//*w ww .j a v a2 s.c o m*/ private void saveImageIntoRealDatabaseAndStorage(String realFilePath) { /** * Add the {@link ItemImageModel} to the server */ // Instantiate the model pass file path and push key as argument ItemImageModel itemImageModel = new ItemImageModel(realFilePath, aaItemMasterPushKey); // Initialize the server location for real time database DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference() .child(aaItemMasterUserUid).child(Constants.FIREBASE_ITEM_MASTER_IMAGE_LOCATION) .child(aaItemMasterPushKey); // Set the value with push() so each itemMaster can have multiple itemImage databaseReference.push().setValue(itemImageModel); /** * Now upload the file to the cloud */ // Initialize storage mImageStorageRef = FirebaseStorage.getInstance().getReference(); // Get reference to the specific storage location to storage the images StorageReference imageStorageRefForUser = mImageStorageRef.child(aaItemMasterUserUid) .child(Constants.FIREBASE_ITEM_MASTER_IMAGE_LOCATION).child(aaItemMasterPushKey); // Get the imagePath from the model then convert imagePath to Uri Uri file = Uri.fromFile(new File(itemImageModel.getImageUrl())); // Pack the Uri object into StorageReference object StorageReference uriRef = imageStorageRefForUser.child(file.getLastPathSegment()); // Create & add file metadata including the content type StorageMetadata metadata = new StorageMetadata.Builder().setContentType("image/jpg").build(); // Upload the file, pass the Uri file and the metadata as argument UploadTask uploadTask = uriRef.putFile(file, metadata); // Register observers to listen for when the upload is done or if it fails uploadTask.addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(@NonNull UploadTask.TaskSnapshot taskSnapshot) { //Uri downloadUrl = taskSnapshot.getDownloadUrl(); } }); }