Example usage for android.net Uri getLastPathSegment

List of usage examples for android.net Uri getLastPathSegment

Introduction

In this page you can find the example usage for android.net Uri getLastPathSegment.

Prototype

@Nullable
public abstract String getLastPathSegment();

Source Link

Document

Gets the decoded last segment in the path.

Usage

From source file:com.example.android.honeypad.ui.HomeActivity.java

/**
 * This method controls both fragments, instructing them to display a
 * certain note.//from   ww w.j  a v a2 s .  c om
 * 
 * @param noteUri The {@link Uri} of the note to show. To create a new note,
 *            pass {@code null}.
 */
private void showNote(final Uri noteUri) {

    if (mTwoPaneView) {
        // check if the NoteEditFragment has been added
        FragmentManager fm = getSupportFragmentManager();
        NoteEditFragment edit = (NoteEditFragment) fm.findFragmentByTag(NOTE_EDIT_TAG);
        final boolean editNoteAdded = (edit != null);

        if (editNoteAdded) {
            if (edit.mCurrentNote != null && edit.mCurrentNote.equals(noteUri)) {
                // clicked on the currently selected note
                return;
            }

            NoteEditFragment editFrag = (NoteEditFragment) fm.findFragmentByTag(NOTE_EDIT_TAG);
            if (noteUri != null) {
                // load an existing note
                editFrag.loadNote(noteUri);
                NoteListFragment list = (NoteListFragment) fm.findFragmentById(R.id.list);
                list.setActivatedNote(Long.valueOf(noteUri.getLastPathSegment()));
            } else {
                // creating a new note - clear the form & list
                // activation
                if (editNoteAdded) {
                    editFrag.clear();
                }
                NoteListFragment list = (NoteListFragment) fm.findFragmentById(R.id.list);
                list.clearActivation();
            }
        } else {
            // add the NoteEditFragment to the container
            FragmentTransaction ft = fm.beginTransaction();
            edit = new NoteEditFragment();
            ft.add(R.id.note_detail_container, edit, NOTE_EDIT_TAG);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.commit();
            edit.loadNote(noteUri);
        }
    } else {
        startActivity(new Intent(NoteEditFragment.ACTION_VIEW_NOTE, noteUri));
    }
}

From source file:com.android.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. ja v  a  2 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("attendeeStatus", 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);
    }

    // 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

/**
 * Updates a label in the labels database.
 *
 * @param uri The URI matching {code LABELS_ID_CONTENT_URI} that represents
 *            the specific label to update.
 * @param values The values to use to update the label.
 * @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 .  j  av  a2  s.  c o  m
 */
@Override
public int update(Uri uri, ContentValues values, 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.update(LabelsTable.TABLE_NAME, values, 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.update(LabelsTable.TABLE_NAME, values,
                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;
    }
}

From source file:com.cttapp.bby.mytlc.layer8apps.CalendarHandler.java

/************
 *  PURPOSE: Adds the parsed out events to the calendar
 *  ARGUMENTS: NULL//from   w  w  w  .  jav a  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;
        }
        }

        createJSONArray(shifts);
        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:Main.java

@SuppressLint("NewApi")
public static String getRealPath(Context context, Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        if (URI_EXTERNAL_DOCUMENTS.equals(uri.getAuthority())) {
            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];
            }//from   w w  w  .  j av a 2s.  c  om
        } else if (URI_DOWNLOAD_DOCUMENTS.equals(uri.getAuthority())) {
            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);
        } else if (URI_MEDIA_DOCUMENTS.equals(uri.getAuthority())) {
            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);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        if (URI_GOOGLE_PHOTOS.equals(uri.getAuthority()))
            return uri.getLastPathSegment();
        return getDataColumn(context, uri, null, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

From source file:com.android.talkback.labeling.LabelProvider.java

/**
 * Queries for a label or multiple labels in the labels database.
 *
 * @param uri The URI representing the type of query to perform:
 *            {@code LABELS_CONTENT_URI} for a subset of all labels,
 *            {@code LABELS_ID_CONTENT_URI} for a specific label, or
 *            {@code PACKAGE_SUMMARY} for a label count per package.
 * @param projection The columns to return.
 * @param selection The WHERE clause for the query.
 * @param selectionArgs The arguments for the WHERE clause of the query.
 * @param sortOrder the ORDER BY clause for the query.
 * @return A cursor representing the data resulting from the query, or]
 *         {@code null} if the query failed to execute.
 *///w  ww  .  j  a  v a  2  s. c  o m
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    if (uri == null) {
        LogUtils.log(this, Log.WARN, NULL_URI_FORMAT_STRING);
        return null;
    }

    if (!UserManagerCompat.isUserUnlocked(getContext())) {
        return null;
    }

    final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(LabelsTable.TABLE_NAME);

    String groupBy = null;

    switch (sUriMatcher.match(uri)) {
    case LABELS:
        if (TextUtils.isEmpty(sortOrder)) {
            sortOrder = LabelsTable.KEY_ID;
        }
        break;
    case LABELS_ID:
        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 null;
        }

        final String where = String.format(Locale.ROOT, "%s = %d", LabelsTable.KEY_ID, labelId);
        queryBuilder.appendWhere(where);
        break;
    case PACKAGE_SUMMARY:
        projection = new String[] { LabelsTable.KEY_PACKAGE_NAME, "COUNT(*)" };
        groupBy = LabelsTable.KEY_PACKAGE_NAME;
        sortOrder = LabelsTable.KEY_PACKAGE_NAME;
        break;
    default:
        LogUtils.log(this, Log.WARN, UNKNOWN_URI_FORMAT_STRING, uri);
        return null;
    }

    initializeDatabaseIfNull();

    return queryBuilder.query(mDatabase, projection, selection, selectionArgs, groupBy, null /* having */,
            sortOrder);
}

From source file:org.spontaneous.trackservice.RemoteService.java

/**
 * Trigged by events that start a new track
 *///  w w  w  .java2 s .  c o  m
private void startNewTrack(Location startLocation, Long userId) {

    this.mTotalDistance = 0;
    this.mDistance = 0;
    ContentValues contentValues = new ContentValues();
    contentValues.put(Tracks.USER_ID, userId);
    Uri newTrack = getContentResolver().insert(Tracks.CONTENT_URI, contentValues);
    this.mTrackId = Long.valueOf(newTrack.getLastPathSegment()).longValue();

    startNewSegment();
    if (startLocation != null) {
        storeLocation(startLocation);
    }
}

From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java

private void trySetupCommentView() {
    mCommentsView.setVerticalScrollBarEnabled(true);
    mCommentsView.setHorizontalScrollBarEnabled(false);
    mCommentsView.setWebViewClient(new WebViewClient() {
        @Override/*ww w.  ja  v  a2  s. co  m*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.startsWith(getString(R.string.uri_prefix_item_comments))) {
                Uri uri = Uri.parse(url);
                String commentId = uri.getQueryParameter("id");
                if ("patch".equals(uri.getLastPathSegment())) {
                    patchComment(commentId);
                } else if ("delete".equals(uri.getLastPathSegment())) {
                    deleteComment(commentId);
                }
                return true;
            }

            return super.shouldOverrideUrlLoading(view, url);
        }
    });
}

From source file:org.spontaneous.trackservice.RemoteService.java

/**
 * Use the ContentResolver mechanism to store a received location
 *
 * @param location/*  www .  j a v a2  s.c o  m*/
 */
private void storeLocation(Location location) {

    if (!isLogging()) {
        Log.e(TAG, String.format("Not logging but storing location %s, prepare to fail", location.toString()));
    }
    ContentValues args = new ContentValues();

    args.put(Waypoints.LATITUDE, Double.valueOf(location.getLatitude()));
    args.put(Waypoints.LONGITUDE, Double.valueOf(location.getLongitude()));
    args.put(Waypoints.SPEED, Float.valueOf(location.getSpeed()));
    args.put(Waypoints.TIME, Long.valueOf(System.currentTimeMillis()));
    args.put(Waypoints.DISTANCE, this.mDistance);

    if (location.hasAccuracy()) {
        args.put(Waypoints.ACCURACY, Float.valueOf(location.getAccuracy()));
    }
    if (location.hasAltitude()) {
        args.put(Waypoints.ALTITUDE, Double.valueOf(location.getAltitude()));

    }
    if (location.hasBearing()) {
        args.put(Waypoints.BEARING, Float.valueOf(location.getBearing()));
    }

    Uri waypointInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI,
            this.mTrackId + "/segments/" + this.mSegmentId + "/waypoints");
    Uri inserted = getContentResolver().insert(waypointInsertUri, args);
    this.mWaypointId = Long.parseLong(inserted.getLastPathSegment());
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

private JSONObject getTemplateFromUri(Uri uri, Collection col) throws JSONException {
    JSONObject model = col.getModels().get(getModelIdFromUri(uri, col));
    Integer ord = Integer.parseInt(uri.getLastPathSegment());
    return model.getJSONArray("tmpls").getJSONObject(ord);
}