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.ichi2.anki.tests.ContentProviderTest.java

/**
 * Initially create one note for each model.
 *///from  w  ww .j a  v  a2s . c o m
@Override
protected void setUp() throws Exception {
    super.setUp();
    Log.i(AnkiDroidApp.TAG, "setUp()");
    mCreatedNotes = new ArrayList<>();
    final Collection col = CollectionHelper.getInstance().getCol(getContext());
    // Add a new basic model that we use for testing purposes (existing models could potentially be corrupted)
    JSONObject model = Models.addBasicModel(col, BASIC_MODEL_NAME);
    mModelId = model.getLong("id");
    ArrayList<String> flds = col.getModels().fieldNames(model);
    // Use the names of the fields as test values for the notes which will be added
    mDummyFields = flds.toArray(new String[flds.size()]);
    // create test decks and add one note for every deck
    final AddContentApi api = new AddContentApi(getContext());
    HashMap<Long, String> deckList = api.getDeckList();
    mNumDecksBeforeTest = deckList.size();
    // TODO: add the notes directly with libanki
    for (int i = 0; i < TEST_DECKS.length; i++) {
        mTestDeckIds[i] = api.addNewDeck(TEST_DECKS[i]);
        Uri newNoteUri = api.addNewNote(mModelId, mTestDeckIds[i], mDummyFields, TEST_TAG);
        assertNotNull(newNoteUri);
        mCreatedNotes.add(newNoteUri);
        // Check that the flds data was set correctly
        long nid = Long.parseLong(newNoteUri.getLastPathSegment());
        Note addedNote = col.getNote(nid);
        assertTrue("Check that the flds data was set correctly",
                Arrays.equals(addedNote.getFields(), mDummyFields));
        assertTrue("Check that there was at least one card generated", addedNote.cards().size() > 0);
    }
    // Add a note to the default deck as well so that testQueryNextCard() works
    Uri newNoteUri = api.addNewNote(mModelId, 1, mDummyFields, TEST_TAG);
    assertNotNull(newNoteUri);
    mCreatedNotes.add(newNoteUri);
}

From source file:com.todoroo.astrid.actfm.EditPeopleControlSet.java

/** Resume save
 * @param data *//*from w  ww  .j  a v  a2  s.  c  o m*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == loginRequestCode && resultCode == Activity.RESULT_OK) {
        // clear user values & reset them to trigger a save
        task.clearValue(Task.USER_ID);
        task.clearValue(Task.USER);
    } else if (requestCode == loginRequestCode) {
        makePrivateTask();
    } else if (requestCode == TaskEditFragment.REQUEST_CODE_CONTACT && resultCode == Activity.RESULT_OK) {
        Uri contactData = data.getData();
        String contactId = contactData.getLastPathSegment();
        String[] args = { contactId };
        String[] projection = { ContactsContract.CommonDataKinds.Email.DATA };
        String selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?"; //$NON-NLS-1$
        Cursor emailCursor = activity.managedQuery(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                projection, selection, args, null);
        if (emailCursor.getCount() > 0) {
            emailCursor.moveToFirst();
            int emailIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
            String email = emailCursor.getString(emailIndex);
            if (!TextUtils.isEmpty(email)) {
                String[] nameProjection = { ContactsContract.Contacts.DISPLAY_NAME };
                Cursor nameCursor = activity.managedQuery(contactData, nameProjection, null, null, null);
                if (nameCursor.getCount() > 0) {
                    nameCursor.moveToFirst();
                    int nameIndex = nameCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                    String name = nameCursor.getString(nameIndex);
                    if (!TextUtils.isEmpty(name)) {
                        StringBuilder fullName = new StringBuilder();
                        fullName.append(name).append(" <").append(email).append('>'); //$NON-NLS-1$
                        email = fullName.toString();
                    }
                }
                assignedCustom.setText(email);
                dontClearAssignedCustom = true;
                refreshDisplayView();
                if (dialog != null)
                    dialog.dismiss();
            } else {
                DialogUtilities.okDialog(activity, activity.getString(R.string.TEA_contact_error), null);
            }
        } else {
            DialogUtilities.okDialog(activity, activity.getString(R.string.TEA_contact_error), null);
        }
    }
}

From source file:com.musenkishi.wally.fragments.SearchFragment.java

@Override
public boolean handleMessage(Message msg) {
    switch (msg.what) {

    case MSG_GET_IMAGES:
        final int index = msg.arg1;
        String query = (String) msg.obj;
        WallyApplication.getDataProviderInstance().getImages(NetworkDataProvider.PATH_SEARCH, query,
                currentColor, index, WallyApplication.getFilterSettings(),
                new DataProvider.OnImagesReceivedListener() {
                    @Override/*from   w  w  w . jav  a 2 s . c om*/
                    public void onImagesReceived(ArrayList<Image> images) {
                        Message msgObj = uiHandler.obtainMessage();
                        msgObj.what = index == 1 ? MSG_IMAGES_REQUEST_CREATE : MSG_IMAGES_REQUEST_APPEND;
                        msgObj.obj = images;
                        uiHandler.sendMessage(msgObj);
                    }

                    @Override
                    public void onError(DataProviderError dataProviderError) {
                        showError(dataProviderError, index);
                    }
                });
        break;

    case MSG_SAVE_BUTTON_CLICKED:
        Image image = (Image) msg.obj;
        WallyApplication.getDataProviderInstance().getPageData(image.imagePageURL(),
                new DataProvider.OnPageReceivedListener() {
                    @Override
                    public void onPageReceived(ImagePage imagePage) {
                        Message msgImagePage = uiHandler.obtainMessage();
                        msgImagePage.what = MSG_PAGE_RECEIVED;
                        msgImagePage.obj = imagePage;
                        uiHandler.sendMessage(msgImagePage);
                    }

                    @Override
                    public void onError(DataProviderError dataProviderError) {
                        Message msgObj = uiHandler.obtainMessage();
                        msgObj.what = MSG_ERROR_IMAGE_SAVING;
                        msgObj.obj = dataProviderError;
                        uiHandler.sendMessage(msgObj);
                    }
                });
        break;

    case MSG_PAGE_RECEIVED:
        ImagePage imagePage = (ImagePage) msg.obj;
        if (imagePage != null) {
            SaveImageRequest saveImageRequest = WallyApplication.getDataProviderInstance()
                    .downloadImageIfNeeded(imagePage.imagePath(), imagePage.imageId(),
                            getResources().getString(R.string.notification_title_image_saving));

            if (saveImageRequest.getDownloadID() != null && getActivity() instanceof MainActivity) {
                WallyApplication.getDownloadIDs().put(saveImageRequest.getDownloadID(), imagePage.imageId());
            } else {
                onFileChange();
            }
        }
        break;

    case MSG_ERROR_IMAGE_REQUEST:
        if (getActivity() != null) {
            DataProviderError dataProviderError = (DataProviderError) msg.obj;
            int imagesIndex = msg.arg1;
            showErrorMessage(dataProviderError, imagesIndex);
        }
        break;

    case MSG_ERROR_IMAGE_SAVING:
        if (getActivity() != null) {
            NotificationProvider notificationProvider = new NotificationProvider();
            notificationProvider.cancelAll(getActivity());
            Toast.makeText(getActivity(), "Couldn't save image", Toast.LENGTH_SHORT).show();
        }
        break;

    case MSG_IMAGES_REQUEST_CREATE:
        ArrayList<Image> images = (ArrayList<Image>) msg.obj;
        boolean shouldScheduleLayoutAnimation = msg.arg1 == 0;
        isLoading = false;
        if (images != null) {
            hideLoader();
            imagesAdapter = new RecyclerImagesAdapter(images, itemSize);
            imagesAdapter.setOnSaveButtonClickedListener(SearchFragment.this);
            imagesAdapter.updateSavedFilesList(savedFiles);
            gridView.setAdapter(imagesAdapter);
            setupAdapter();
            if (shouldScheduleLayoutAnimation) {
                gridView.scheduleLayoutAnimation();
            }
        }
        break;

    case MSG_IMAGES_REQUEST_APPEND:
        ArrayList<Image> extraImages = (ArrayList<Image>) msg.obj;
        isLoading = false;
        if (extraImages != null) {
            hideLoader();
            int endPosition = imagesAdapter.getItemCount();
            ArrayList<Image> currentList = imagesAdapter.getImages();
            currentList.addAll(extraImages);
            imagesAdapter.notifyItemRangeInserted(endPosition, extraImages.size());
        }
        break;

    case MSG_GET_LIST_OF_SAVED_IMAGES:
        HashMap<String, Boolean> existingFiles = new HashMap<String, Boolean>();

        FileManager fileManager = new FileManager();
        for (Uri uri : fileManager.getFiles()) {
            String filename = uri.getLastPathSegment();
            String[] filenames = filename.split("\\.(?=[^\\.]+$)"); //split filename from it's extension
            existingFiles.put(filenames[0], true);
        }

        Message fileListMessage = uiHandler.obtainMessage();
        fileListMessage.obj = existingFiles;
        fileListMessage.what = MSG_SAVE_LIST_OF_SAVED_IMAGES;
        uiHandler.sendMessage(fileListMessage);
        break;

    case MSG_SAVE_LIST_OF_SAVED_IMAGES:
        savedFiles = (HashMap<String, Boolean>) msg.obj;
        if (imagesAdapter != null) {
            imagesAdapter.updateSavedFilesList(savedFiles);
            imagesAdapter.notifySavedItemsChanged();
        }
        break;

    case MSG_NEW_COLOR_FETCHED:
        int color = msg.arg1;
        String colorHex = Integer.toHexString(color).substring(2);
        int[] colors = new int[1];
        colors[0] = color;
        Bitmap bitmapColor = Bitmap.createBitmap(colors, 1, 1, Bitmap.Config.ARGB_8888); //Use this to create a Palette.
        Palette palette = Palette.generate(bitmapColor);

        Message newColorMessage = uiHandler.obtainMessage();
        newColorMessage.what = MSG_RENDER_NEW_COLOR;
        newColorMessage.obj = new Pair<String, Palette>(colorHex, palette);
        uiHandler.sendMessage(newColorMessage);
        break;

    case MSG_RENDER_NEW_COLOR:
        Pair<String, Palette> pair = (Pair<String, Palette>) msg.obj;
        String colorAsHex = pair.first;
        Palette palette1 = pair.second;

        showColorTag(colorAsHex, palette1);

        break;
    }
    return false;
}

From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java

protected void putSign() {
    LinearLayout layout = (LinearLayout) findViewById(R.id.controls_list);
    for (int i = 0; i < layout.getChildCount(); i++) {
        View child = layout.getChildAt(i);
        if (child instanceof Sign) {
            IGISApplication application = (IGISApplication) getApplication();
            Uri uri = Uri.parse("content://" + application.getAuthority() + "/" + mLayer.getPath().getName()
                    + "/" + mFeatureId + "/" + Constants.URI_ATTACH);

            ContentValues values = new ContentValues();
            values.put(VectorLayer.ATTACH_DISPLAY_NAME, "_signature");
            values.put(VectorLayer.ATTACH_DESCRIPTION, "_signature");
            values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");

            Cursor saved = getContentResolver().query(uri, null, VectorLayer.ATTACH_ID + " =  ?",
                    new String[] { Sign.SIGN_FILE }, null);
            boolean hasSign = false;
            if (saved != null) {
                hasSign = saved.moveToFirst();
                saved.close();//  w  w w .  j  a  v a 2  s .  c o  m
            }

            if (!hasSign) {
                Uri result = getContentResolver().insert(uri, values);
                if (result != null) {
                    long id = Long.parseLong(result.getLastPathSegment());
                    values.clear();
                    values.put(VectorLayer.ATTACH_ID, Integer.MAX_VALUE);
                    uri = Uri.withAppendedPath(uri, id + "");
                    getContentResolver().update(uri, values, null, null);
                }
            }

            File png = new File(mLayer.getPath(), mFeatureId + "");
            Sign sign = (Sign) child;
            try {
                if (!png.isDirectory())
                    FileUtil.createDir(png);

                png = new File(png, Sign.SIGN_FILE);
                sign.save(sign.getWidth(), sign.getHeight(), true, png);
            } catch (IOException | RuntimeException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.mariotaku.twidere.service.BackgroundOperationService.java

private void handleUpdateStatusIntent(final Intent intent) {
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    final ParcelableStatusUpdate status = intent.getParcelableExtra(EXTRA_STATUS);
    final Parcelable[] status_parcelables = intent.getParcelableArrayExtra(EXTRA_STATUSES);
    final ParcelableStatusUpdate[] statuses;
    if (status_parcelables != null) {
        statuses = new ParcelableStatusUpdate[status_parcelables.length];
        for (int i = 0, j = status_parcelables.length; i < j; i++) {
            statuses[i] = (ParcelableStatusUpdate) status_parcelables[i];
        }/*  ww w . j  a  v  a 2s. c  o m*/
    } else if (status != null) {
        statuses = new ParcelableStatusUpdate[1];
        statuses[0] = status;
    } else
        return;
    startForeground(NOTIFICATION_ID_UPDATE_STATUS, updateUpdateStatusNotification(this, builder, 0, null));
    for (final ParcelableStatusUpdate item : statuses) {
        mNotificationManager.notify(NOTIFICATION_ID_UPDATE_STATUS,
                updateUpdateStatusNotification(this, builder, 0, item));
        final ContentValues draftValues = ContentValuesCreator.createStatusDraft(item,
                ParcelableAccount.getAccountIds(item.accounts));
        final Uri draftUri = mResolver.insert(Drafts.CONTENT_URI, draftValues);
        final long draftId = ParseUtils.parseLong(draftUri.getLastPathSegment(), -1);
        mTwitter.addSendingDraftId(draftId);
        final List<SingleResponse<ParcelableStatus>> result = updateStatus(builder, item);
        boolean failed = false;
        Exception exception = null;
        final Expression where = Expression.equals(Drafts._ID, draftId);
        final List<Long> failedAccountIds = ListUtils.fromArray(ParcelableAccount.getAccountIds(item.accounts));

        for (final SingleResponse<ParcelableStatus> response : result) {

            if (response.getData() == null) {
                failed = true;
                if (exception == null) {
                    exception = response.getException();
                }
            } else if (response.getData().account_id > 0) {
                failedAccountIds.remove(response.getData().account_id);
                //spice
                if (response.getData().media == null) {
                    SpiceProfilingUtil.log(response.getData().id + ",Tweet," + response.getData().account_id
                            + "," + response.getData().in_reply_to_user_id + ","
                            + response.getData().in_reply_to_status_id);
                    SpiceProfilingUtil.profile(this.getBaseContext(), response.getData().account_id,
                            response.getData().id + ",Tweet," + response.getData().account_id + ","
                                    + response.getData().in_reply_to_user_id + ","
                                    + response.getData().in_reply_to_status_id);
                } else
                    for (final ParcelableMedia spiceMedia : response.getData().media) {
                        SpiceProfilingUtil.log(response.getData().id + ",Media," + response.getData().account_id
                                + "," + response.getData().in_reply_to_user_id + ","
                                + response.getData().in_reply_to_status_id + "," + spiceMedia.media_url + ","
                                + TypeMappingUtil.getMediaType(spiceMedia.type));
                        SpiceProfilingUtil.profile(this.getBaseContext(), response.getData().account_id,
                                response.getData().id + ",Media," + response.getData().account_id + ","
                                        + response.getData().in_reply_to_user_id + ","
                                        + response.getData().in_reply_to_status_id + "," + spiceMedia.media_url
                                        + "," + TypeMappingUtil.getMediaType(spiceMedia.type));
                    }
                //end
            }
        }

        if (result.isEmpty()) {
            showErrorMessage(R.string.action_updating_status, getString(R.string.no_account_selected), false);
        } else if (failed) {
            // If the status is a duplicate, there's no need to save it to
            // drafts.
            if (exception instanceof TwitterException && ((TwitterException) exception)
                    .getErrorCode() == StatusCodeMessageUtils.STATUS_IS_DUPLICATE) {
                showErrorMessage(getString(R.string.status_is_duplicate), false);
            } else {
                final ContentValues accountIdsValues = new ContentValues();
                accountIdsValues.put(Drafts.ACCOUNT_IDS, ListUtils.toString(failedAccountIds, ',', false));
                mResolver.update(Drafts.CONTENT_URI, accountIdsValues, where.getSQL(), null);
                showErrorMessage(R.string.action_updating_status, exception, true);
                displayTweetNotSendNotification();
            }
        } else {
            showOkMessage(R.string.status_updated, false);
            mResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
            if (item.media != null) {
                for (final ParcelableMediaUpdate media : item.media) {
                    final String path = getImagePathFromUri(this, Uri.parse(media.uri));
                    if (path != null) {
                        if (!new File(path).delete()) {
                            Log.d(LOGTAG, String.format("unable to delete %s", path));
                        }
                    }
                }
            }
        }
        mTwitter.removeSendingDraftId(draftId);
        if (mPreferences.getBoolean(KEY_REFRESH_AFTER_TWEET, false)) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTwitter.refreshAll();
                }
            });
        }
    }
    stopForeground(false);
    mNotificationManager.cancel(NOTIFICATION_ID_UPDATE_STATUS);
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBBase.java

/**
 * Query records from the database./* ww w. j a  va  2s .c  o  m*/
 *
 * @param uri A Uri indicating which part of data to query.
 * @param projection The projection of columns.
 * @param selection The "where" clause of sql.
 * @param selectionArgs Strings in the "where" clause.
 * @param sortOrder Sorting order of the query.
 * @param type Type of transfers to query.
 * @return A Cursor pointing to records.
 */
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    // TODO: currently all methods calling this pass null to projection.
    // In the future we want to update projection to be more specific for
    // performance and must handle that here.
    queryBuilder.setTables(TransferTable.TABLE_TRANSFER);
    final int uriType = uriMatcher.match(uri);
    switch (uriType) {
    case TRANSFERS:
        queryBuilder.appendWhere(TransferTable.COLUMN_PART_NUM + "=" + 0);
        break;
    case TRANSFER_ID:
        queryBuilder.appendWhere(TransferTable.COLUMN_ID + "=" + uri.getLastPathSegment());
        break;
    case TRANSFER_PART:
        queryBuilder.appendWhere(TransferTable.COLUMN_MAIN_UPLOAD_ID + "=" + uri.getLastPathSegment());
        break;
    case TRANSFER_STATE:
        queryBuilder.appendWhere(TransferTable.COLUMN_STATE + "=");
        queryBuilder.appendWhereEscapeString(uri.getLastPathSegment());
        break;
    default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    ensureDatabaseOpen();
    final Cursor cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null,
            sortOrder);
    return cursor;
}

From source file:org.getlantern.firetweet.service.BackgroundOperationService.java

private void handleDiscardDraftIntent(Intent intent) {
    final Uri data = intent.getData();
    if (data == null)
        return;/*from   w ww.ja  v  a2 s .  co  m*/
    mNotificationManager.cancel(data.toString(), NOTIFICATION_ID_DRAFTS);
    final ContentResolver contentResolver = getContentResolver();
    final long id = ParseUtils.parseLong(data.getLastPathSegment(), -1);
    final Expression where = Expression.equals(Drafts._ID, id);
    contentResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
}

From source file:com.nbplus.hybrid.BasicWebViewClient.java

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // for excel download
    if (isDocumentMimeType(url)) {
        Log.d(TAG, "This url is document mimetype = " + url);
        if (StorageUtils.isExternalStorageWritable()) {
            Uri source = Uri.parse(url);

            // Make a new request pointing to the mp3 url
            DownloadManager.Request request = new DownloadManager.Request(source);
            // Use the same file name for the destination
            File destinationFile = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    source.getLastPathSegment());
            request.setDestinationUri(Uri.fromFile(destinationFile));
            // Add it to the manager
            mDownloadManager.enqueue(request);
            Toast.makeText(mContext, R.string.downloads_requested, Toast.LENGTH_SHORT).show();
        } else {/*from w ww .  j a v a  2 s.c om*/
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setPositiveButton("?", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //closeWebApplication();
                }
            });
            builder.setMessage(R.string.downloads_path_check);
            builder.show();
        }
        return true;
    }

    if (url.startsWith("tel:")) {
        // phone call
        if (!PhoneState.hasPhoneCallAbility(mContext)) {
            Log.d(TAG, ">> This device has not phone call ability !!!");
            return true;
        }

        mContext.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
    } else if (url.startsWith("mailto:")) {
        url = url.replaceFirst("mailto:", "");
        url = url.trim();

        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[] { url });

        mContext.startActivity(i);
    } else if (url.startsWith("geo:")) {
        Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        mContext.startActivity(searchAddress);
    } else {
        //  URL ??   ? ??? .
        dismissProgressDialog();
        loadWebUrl(url);
        showProgressDialog();
    }
    return true;
}

From source file:com.granita.tasks.TaskListFragment.java

/** Returns the position of the task in the cursor. Returns -1 if the task is not in the cursor **/
private int getSelectedChildPostion(Uri taskUri, Cursor listCursor) {
    if (taskUri != null && listCursor != null && listCursor.moveToFirst()) {
        Long taskIdToSelect = Long.valueOf(taskUri.getLastPathSegment());
        do {/*  ww w .ja  v a 2s.c om*/
            Long taskId = listCursor.getLong(listCursor.getColumnIndex(Tasks._ID));
            if (taskId.equals(taskIdToSelect)) {
                return listCursor.getPosition();
            }
        } while (listCursor.moveToNext());
    }
    return -1;
}

From source file:org.kontalk.ui.ComposeMessage.java

private AbstractComposeFragment getComposeFragment(Bundle savedInstanceState) {
    Bundle args = processIntent(savedInstanceState);
    if (args != null) {
        AbstractComposeFragment f = null;
        Uri threadUri = args.getParcelable("data");
        String action = args.getString("action");
        if (ACTION_VIEW_CONVERSATION.equals(action)) {
            long threadId = ContentUris.parseId(threadUri);
            Conversation conv = Conversation.loadFromId(this, threadId);
            if (conv != null) {
                f = conv.isGroupChat() ? new GroupMessageFragment() : new ComposeMessageFragment();
            }/*w ww . j av a 2s .co  m*/
        } else if (ACTION_VIEW_USERID.equals(action)) {
            String userId = threadUri.getLastPathSegment();
            Conversation conv = Conversation.loadFromUserId(this, userId);
            f = conv != null && conv.isGroupChat() ? new GroupMessageFragment() : new ComposeMessageFragment();
        } else {
            // default to a single user chat
            f = new ComposeMessageFragment();
        }

        if (f != null)
            f.setArguments(args);
        return f;
    }

    return null;
}