List of usage examples for android.net Uri getLastPathSegment
@Nullable public abstract String getLastPathSegment();
From source file:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java
/** Called when a session detail view asks to send session results somewhere. * Generates a link to the session report Uri, and lets the remote program read from it. * The {@link RhetologContentProvider} generates the result file on demand. * /* w ww. j a va2 s.com*/ * */ @Override public void onSessionSend(Context context, Uri session) { // Send to the program selected by the chooser below. Intent sendSession = new Intent(Intent.ACTION_SEND); // Permit to read from Rhetolog URIs. sendSession.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Note type of send as report. sendSession.setType(RhetologContract.RHETOLOG_TYPE_SESSION_REPORT); sendSession.putExtra(Intent.EXTRA_SUBJECT, "Sending session " + session); // Send text as text. sendSession.putExtra(Intent.EXTRA_TEXT, reportForSession(session)); // Send text as URI to be read. sendSession.putExtra(Intent.EXTRA_STREAM, Uri.parse(RhetologContract.SESSIONSREPORT + "/" + session.getLastPathSegment())); // Permit user to choose target of send. context.startActivity(Intent.createChooser(sendSession, "Send session results")); }
From source file:org.mobisocial.corral.ContentCorral.java
public static Uri storeContent(Context context, Uri contentUri, String type) { File contentDir;//from ww w . j a v a 2s. c om if (type != null && (type.startsWith("image/") || type.startsWith("video/"))) { contentDir = new File(Environment.getExternalStorageDirectory(), PICTURE_SUBFOLDER); } else { contentDir = new File(Environment.getExternalStorageDirectory(), FILES_SUBFOLDER); } if (!contentDir.exists() && !contentDir.mkdirs()) { Log.e(TAG, "failed to create musubi corral directory"); return null; } int timestamp = (int) (System.currentTimeMillis() / 1000L); String ext = CorralDownloadClient.extensionForType(type); String fname = timestamp + "-" + contentUri.getLastPathSegment() + "." + ext; File copy = new File(contentDir, fname); FileOutputStream out = null; InputStream in = null; try { contentDir.mkdirs(); in = context.getContentResolver().openInputStream(contentUri); BufferedInputStream bin = new BufferedInputStream(in); byte[] buff = new byte[1024]; out = new FileOutputStream(copy); int r; while ((r = bin.read(buff)) > 0) { out.write(buff, 0, r); } bin.close(); return Uri.fromFile(copy); } catch (IOException e) { Log.w(TAG, "Error copying file", e); if (copy.exists()) { copy.delete(); } return null; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { Log.e(TAG, "failed to close handle on store corral content", e); } } }
From source file:com.layer8apps.CalendarHandler.java
/************ * PURPOSE: Adds the parsed out events to the calendar * ARGUMENTS: NULL//from ww w.j a va 2 s. c o m * RETURNS: VOID * AUTHOR: Devin Collins <agent14709@gmail.com>, Bobby Ore <bob1987@gmail.com> *************/ private int addDays() { ArrayList<Shift> shifts = buildShifts(); try { // deleteOldEvents(); Preferences pf = new Preferences(this); // Get our stored notification time int notification = pf.getNotification(); // Convert the stored time into minutes switch (notification) { case 0: { notification = 0; break; } case 1: { notification = 5; break; } case 2: { notification = 15; break; } case 3: { notification = 30; break; } case 4: { notification = 60; break; } case 5: { notification = 120; break; } case 6: { notification = 180; break; } } shifts = checkForDuplicates(shifts); if (shifts.size() == 0) { return 0; } TimeZone zone = TimeZone.getDefault(); for (Shift shift : shifts) { /************ * ContentResolver and ContentValues are what we use to add * our calendar events to the device *************/ ContentResolver cr = this.getContentResolver(); ContentValues cv = new ContentValues(); /************ * Here we create our calendar event based on the version code *************/ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { cv.put(CalendarContract.Events.CALENDAR_ID, calID); cv.put(CalendarContract.Events.DESCRIPTION, shift.getDepartment()); cv.put(CalendarContract.Events.DTEND, shift.getEndDate().getTimeInMillis()); cv.put(CalendarContract.Events.DTSTART, shift.getStartDate().getTimeInMillis()); cv.put(CalendarContract.Events.EVENT_LOCATION, shift.getAddress()); cv.put(CalendarContract.Events.EVENT_TIMEZONE, zone.getID()); cv.put(CalendarContract.Events.HAS_ALARM, (notification == 0) ? 0 : 1); cv.put(CalendarContract.Events.TITLE, shift.getTitle()); } else { cv.put("calendar_id", calID); cv.put("description", shift.getDepartment()); cv.put("dtend", shift.getEndDate().getTimeInMillis()); cv.put("dtstart", shift.getStartDate().getTimeInMillis()); cv.put("eventLocation", shift.getAddress()); cv.put("eventTimezone", zone.getID()); cv.put("title", shift.getTitle()); cv.put("hasAlarm", (notification <= 0) ? 0 : 1); } /************ * Add our events to the calendar based on the Uri we get *************/ Uri uri = cr.insert(getEventsUri(), cv); if (uri == null) { continue; } // Get the ID of the calendar event long eventID = Long.parseLong(uri.getLastPathSegment()); pf.saveShift(String.valueOf(eventID)); /************ * If we retrieved a Uri for the event, try to add the reminder *************/ if (notification > 0) { /************ * Build our reminder based on version code *************/ ContentValues reminders = new ContentValues(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { reminders.put(CalendarContract.Reminders.EVENT_ID, eventID); reminders.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); reminders.put(CalendarContract.Reminders.MINUTES, notification); } else { reminders.put("event_id", eventID); reminders.put("method", 1); reminders.put("minutes", notification); } // Add the reminder to the system cr.insert(getRemindersUri(), reminders); } } } catch (Exception e) { showError( "Could not create calendar events on calendar, please make sure you have a calendar application on your device"); return -1; } return shifts.size(); }
From source file:can.yrt.onebusaway.ArrivalsListFragment.java
private void setStopId() { Uri uri = (Uri) getArguments().getParcelable(FragmentUtils.URI); if (uri == null) { Log.e(TAG, "No URI in arguments"); return;// w w w.j ava2 s . co m } mStopId = uri.getLastPathSegment(); mStopUri = uri; }
From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase sqLiteDatabase = mDatabaseHelper.getWritableDatabase(); String tableName;/*from w w w .ja v a 2s.c o m*/ String where; String order = ""; Bundle bundleSyncAdapter = new Bundle(); String lastPathSegment = uri.getLastPathSegment(); if (StringUtils.isNotBlank(sortOrder)) { order = " ORDER BY " + sortOrder; } switch (URI_MATCHER.match(uri)) { // Getting the content for a group (list of simple data) case CatalogContract.Provider.CODE_GROUP_ID: tableName = CatalogContract.DataBaseDataSimple.TABLE_NAME; where = CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + "." + CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "='" + lastPathSegment + "'"; // Limit for the query on the sync adapter String currentPage = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_CURRENT_PAGE); String pageSize = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_PAGE_SIZE); // Bundle information for the syncing part bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, lastPathSegment); if (StringUtils.isNotBlank(currentPage) && StringUtils.isNotBlank(pageSize)) { bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE, Integer.valueOf(currentPage)); bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, Integer.valueOf(pageSize)); } break; // Getting a specific data detail case CatalogContract.Provider.CODE_DATA_ID: case CatalogContract.Provider.CODE_DATA_DETAILS_ID: tableName = CatalogContract.DataBaseDataDetails.TABLE_NAME; where = CatalogContract.DataBaseDataDetails.TABLE_NAME + "." + CatalogContract.DataBaseDataDetails.ATT_DATA_ID + "='" + lastPathSegment + "'"; // Bundle information for the syncing part bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_DATA_ID, lastPathSegment); // We don't load the variants for a specific data bundleSyncAdapter.putBoolean(CatalogSyncConstants.SYNC_PARAM_LOAD_VARIANTS, false); break; default: Log.e(TAG, "URI not recognized" + uri.toString()); throw new IllegalArgumentException("URI not recognized" + uri.toString()); } // We do the query by joining the data to the group Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + tableName + " INNER JOIN " + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + " ON " + tableName + "." + CatalogContract.DataBaseData.ATT_DATA_ID + "=" + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + "." + CatalogContract.DataBaseDataLinkGroup.ATT_DATA_ID + " WHERE " + where + order, null); // Register the cursor to watch the uri for changes cursor.setNotificationUri(getContext().getContentResolver(), uri); // Existing data if (cursor.getCount() > 0) { // TODO - For now we check if one the items is out-of-sync and we sync all of them if this is the case // Future - Check every out-of-date items and sync them cursor.moveToLast(); int status = cursor.getInt(cursor.getColumnIndex(CatalogContract.DataBaseData.ATT_STATUS)); cursor.moveToFirst(); // Data expired, we request a sync if (status == CatalogContract.SyncStatus.OUTOFDATE.getValue()) { Log.i(TAG, "Data for " + uri.toString() + " is out-of-date, requesting a sync"); requestSync(bundleSyncAdapter); // TODO - the uptodate/outofdate should be done in the sync adapter // We up-to-date all the data in case the sync does not return any results (we base our out of sync on the last item of the cursor) if (URI_MATCHER.match(uri) == CatalogContract.Provider.CODE_GROUP_ID) { updateInternalDataSyncStatus(cursor, tableName, SyncStatus.UPTODATE); } } // Data updated, we invalidate the data else { Log.i(TAG, "Data for " + uri.toString() + " is up-of-date, invalidating it"); updateInternalDataSyncStatus(cursor, tableName, SyncStatus.OUTOFDATE); } } // No data found, we request a sync if it's not already up-to-date else { boolean triggerSyncAdapter; switch (URI_MATCHER.match(uri)) { // Saving the sync info for the group case CatalogContract.Provider.CODE_GROUP_ID: triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriSyncGroup(authority), CatalogContract.DataBaseSyncStatusGroup.ATT_GROUP_ID, CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, lastPathSegment); break; // Saving the sync info for the data case CatalogContract.Provider.CODE_DATA_ID: triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriData(authority), CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataSimple.TABLE_NAME, lastPathSegment); break; // Saving the sync info for the data details case CatalogContract.Provider.CODE_DATA_DETAILS_ID: triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriDataDetails(authority), CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataDetails.TABLE_NAME, lastPathSegment); break; default: Log.e(TAG, "URI not recognized" + uri.toString()); throw new IllegalArgumentException("URI not recognized" + uri.toString()); } // Trigger the sync adapter if (triggerSyncAdapter) { Log.i(TAG, "No data found for " + uri.toString() + " and data out-of-date, requesting a sync"); requestSync(bundleSyncAdapter); } else { Log.i(TAG, "No data found for " + uri.toString() + " and data up-to-date"); } } return cursor; }
From source file:com.hivewallet.androidclient.wallet.AddressBookProvider.java
@Override public Cursor query(final Uri uri, final String[] projection, final String originalSelection, final String[] originalSelectionArgs, final String sortOrder) { final SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(DATABASE_TABLE);/*from ww w.ja va 2 s . c o m*/ final List<String> pathSegments = uri.getPathSegments(); if (pathSegments.size() > 1) throw new IllegalArgumentException(uri.toString()); String selection = null; String[] selectionArgs = null; if (pathSegments.size() == 1) { final String address = uri.getLastPathSegment(); qb.appendWhere(KEY_ADDRESS + "="); qb.appendWhereEscapeString(address); } else if (SELECTION_IN.equals(originalSelection)) { final String[] addresses = originalSelectionArgs[0].trim().split(","); qb.appendWhere(KEY_ADDRESS + " IN ("); appendAddresses(qb, addresses); qb.appendWhere(")"); } else if (SELECTION_NOTIN.equals(originalSelection)) { final String[] addresses = originalSelectionArgs[0].trim().split(","); qb.appendWhere(KEY_ADDRESS + " NOT IN ("); appendAddresses(qb, addresses); qb.appendWhere(")"); } else if (SELECTION_QUERY.equals(originalSelection)) { final String query = '%' + originalSelectionArgs[0].trim() + '%'; selection = KEY_ADDRESS + " LIKE ? OR " + KEY_LABEL + " LIKE ?"; selectionArgs = new String[] { query, query }; } final Cursor cursor = qb.query(helper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; }
From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java
protected boolean saveFeature() { if (mLayer == null) { Toast.makeText(this, R.string.error_layer_not_inited, Toast.LENGTH_SHORT).show(); return false; }/*from ww w.java2 s . c o m*/ //create new row or modify existing List<Field> fields = mLayer.getFields(); ContentValues values = new ContentValues(); for (Field field : fields) { putFieldValue(values, field); } putGeometry(values); IGISApplication app = (IGISApplication) getApplication(); if (null == app) { throw new IllegalArgumentException("Not a IGISApplication"); } Uri uri = Uri.parse("content://" + app.getAuthority() + "/" + mLayer.getPath().getName()); boolean error; if (mFeatureId == NOT_FOUND) { // we need to get proper mFeatureId for new features first Uri result = getContentResolver().insert(uri, values); if (error = result == null) Toast.makeText(this, getText(R.string.error_db_insert), Toast.LENGTH_SHORT).show(); else mFeatureId = Long.parseLong(result.getLastPathSegment()); } else { Uri updateUri = ContentUris.withAppendedId(uri, mFeatureId); boolean valuesUpdated = getContentResolver().update(updateUri, values, null, null) == 1; if (error = !valuesUpdated) Toast.makeText(this, getText(R.string.error_db_update), Toast.LENGTH_SHORT).show(); } putAttaches(); putSign(); Intent data = new Intent(); data.putExtra(ConstantsUI.KEY_FEATURE_ID, mFeatureId); setResult(RESULT_OK, data); return !error; }
From source file:org.odk.collect.android.logic.FormRelationsManager.java
/** * Gets the id in the InstanceProvider for a given instance. * * @param instance The Uri for/*from w ww . ja v a 2 s. co m*/ * @return Returns the id in the InstanceProvider for a given instance. * Returns -1 if no corresponding id is found. */ private static long getIdFromSingleUri(Uri instance) { long id = -1; if (Collect.getInstance().getContentResolver().getType(instance) .equals(InstanceColumns.CONTENT_ITEM_TYPE)) { String idStr = instance.getLastPathSegment(); id = Long.parseLong(idStr); } else if (Collect.getInstance().getContentResolver().getType(instance) .equals(FormsColumns.CONTENT_ITEM_TYPE)) { // if uri is for a form // first try to find by looking up absolute path FormController formController = Collect.getInstance().getFormController(); String[] projection = { InstanceColumns._ID }; String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String instancePath = formController.getInstancePath().getAbsolutePath(); String[] selectionArgs = { instancePath }; Cursor c = Collect.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, projection, selection, selectionArgs, null); if (c != null) { if (c.getCount() > 0) { c.moveToFirst(); id = c.getLong(c.getColumnIndex(InstanceColumns._ID)); } c.close(); } } return id; }
From source file:com.xandy.calendar.EventInfoActivity.java
@Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // Get the info needed for the fragment Intent intent = getIntent();/*from w ww. j av a2 s . co m*/ int attendeeResponse = 0; mEventId = -1; boolean isDialog = false; ArrayList<ReminderEntry> reminders = null; if (icicle != null) { mEventId = icicle.getLong(EventInfoFragment.BUNDLE_KEY_EVENT_ID); mStartMillis = icicle.getLong(EventInfoFragment.BUNDLE_KEY_START_MILLIS); mEndMillis = icicle.getLong(EventInfoFragment.BUNDLE_KEY_END_MILLIS); attendeeResponse = icicle.getInt(EventInfoFragment.BUNDLE_KEY_ATTENDEE_RESPONSE); isDialog = icicle.getBoolean(EventInfoFragment.BUNDLE_KEY_IS_DIALOG); reminders = Utils.readRemindersFromBundle(icicle); } else if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) { mStartMillis = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, 0); mEndMillis = intent.getLongExtra(EXTRA_EVENT_END_TIME, 0); attendeeResponse = intent.getIntExtra(ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_NONE); Uri data = intent.getData(); if (data != null) { try { List<String> pathSegments = data.getPathSegments(); int size = pathSegments.size(); if (size > 2 && "EventTime".equals(pathSegments.get(2))) { // Support non-standard VIEW intent format: //dat = content://com.android.calendar/events/[id]/EventTime/[start]/[end] mEventId = Long.parseLong(pathSegments.get(1)); if (size > 4) { mStartMillis = Long.parseLong(pathSegments.get(3)); mEndMillis = Long.parseLong(pathSegments.get(4)); } } else { mEventId = Long.parseLong(data.getLastPathSegment()); } } catch (NumberFormatException e) { if (mEventId == -1) { // do nothing here , deal with it later } else if (mStartMillis == 0 || mEndMillis == 0) { // Parsing failed on the start or end time , make sure the times were not // pulled from the intent's extras and reset them. mStartMillis = 0; mEndMillis = 0; } } } } if (mEventId == -1) { Log.w(TAG, "No event id"); Toast.makeText(this, R.string.event_not_found, Toast.LENGTH_SHORT).show(); finish(); } // If we do not support showing full screen event info in this configuration, // close the activity and show the event in AllInOne. Resources res = getResources(); if (!res.getBoolean(R.bool.agenda_show_event_info_full_screen) && !res.getBoolean(R.bool.show_event_info_full_screen)) { CalendarController.getInstance(this).launchViewEvent(mEventId, mStartMillis, mEndMillis, attendeeResponse); finish(); return; } setContentView(R.layout.simple_frame_layout); // Get the fragment if exists mInfoFragment = (EventInfoFragment) getSupportFragmentManager().findFragmentById(R.id.main_frame); // Remove the application title ActionBar bar = getActionBar(); if (bar != null) { bar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME); } // Create a new fragment if none exists if (mInfoFragment == null) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); mInfoFragment = new EventInfoFragment(this, mEventId, mStartMillis, mEndMillis, attendeeResponse, isDialog, (isDialog ? EventInfoFragment.DIALOG_WINDOW_STYLE : EventInfoFragment.FULL_WINDOW_STYLE), reminders); ft.replace(R.id.main_frame, mInfoFragment); ft.commit(); } }
From source file:com.android.talkback.labeling.LabelProvider.java
/** * Deletes a label in the labels database. * * @param uri The URI matching {code LABELS_ID_CONTENT_URI} that represents * the specific label to delete. * @param selection The WHERE clause for the query. * @param selectionArgs The arguments for the WHERE clause of the query. * @return The number of rows affected.//from w w w . ja va 2s . c o m */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (uri == null) { LogUtils.log(this, Log.WARN, NULL_URI_FORMAT_STRING); return 0; } if (!UserManagerCompat.isUserUnlocked(getContext())) { return 0; } switch (sUriMatcher.match(uri)) { case LABELS: { initializeDatabaseIfNull(); int result = mDatabase.delete(LabelsTable.TABLE_NAME, selection, selectionArgs); getContext().getContentResolver().notifyChange(uri, null /* observer */); return result; } case LABELS_ID: { initializeDatabaseIfNull(); final String labelIdString = uri.getLastPathSegment(); final int labelId; try { labelId = Integer.parseInt(labelIdString); } catch (NumberFormatException e) { LogUtils.log(this, Log.WARN, UNKNOWN_URI_FORMAT_STRING, uri); return 0; } final String where = String.format(Locale.ROOT, "%s = %d", LabelsTable.KEY_ID, labelId); final int result = mDatabase.delete(LabelsTable.TABLE_NAME, combineSelectionAndWhere(selection, where), selectionArgs); getContext().getContentResolver().notifyChange(uri, null /* observer */); return result; } default: LogUtils.log(this, Log.WARN, UNKNOWN_URI_FORMAT_STRING, uri); return 0; } }