Example usage for android.net Uri toString

List of usage examples for android.net Uri toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Document

Returns the encoded string representation of this URI.

Usage

From source file:com.popcorntime.apps.remote.utils.Utils.java

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Log.i("uri", contentUri.toString());
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        Cursor cursor = null;/*w ww  . j  a  va 2s  .com*/
        try {

            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } else {
        Uri uri = contentUri;
        // DocumentProvider
        if (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];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri2 = ContentUris
                        .withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri2, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri2 = null;
                if ("image".equals(type)) {
                    contentUri2 = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    //contentUri2 = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    //contentUri2 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] { split[1] };

                return getDataColumn(context, contentUri2, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
}

From source file:com.scvngr.levelup.core.net.AbstractRequest.java

/**
 * @param url the URL whose query parameters will be extracted.
 * @return a map of the query parameters or null if there is an error parsing the URL.
 *///from   w w w . j a v  a 2s . c  om
@Nullable
private static Map<String, String> extractQueryParameters(final Uri url) {
    Map<String, String> params = null;

    try {
        final List<NameValuePair> paramsList = URLEncodedUtils.parse(new URI(url.toString()), "utf-8");
        params = new HashMap<String, String>(paramsList.size());

        for (final NameValuePair nvp : paramsList) {
            params.put(nvp.getName(), nvp.getValue());
        }
    } catch (final URISyntaxException e) {
        // failsafe
        LogManager.e(NullUtils.format("could not parse uri: '%s'. " + "dropping query parameters.", url), e);
    }

    return params;
}

From source file:com.antew.redditinpictures.library.service.RESTService.java

private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {/*from   ww  w .j a  v a2s.c om*/
        if (params == null) {
            // No params were given or they have already been
            // attached to the Uri.
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect: %s", uri.toString());
    }
}

From source file:com.apptentive.android.sdk.module.messagecenter.ApptentiveMessageCenter.java

/**
 * @param context The Activity Context that launched this view.
 *//*from   w  ww  . jav  a2 s .c om*/
public static void doShow(final Context context) {
    if (!(context instanceof Activity)) {
        Log.e(ApptentiveMessageCenter.class.getSimpleName() + " must be initialized with an Activity Context.");
        return;
    }

    MetricModule.sendMetric(context, Event.EventLabel.message_center__launch,
            (trigger == null ? null : trigger.name()));

    MessageCenterView.OnSendMessageListener onSendMessagelistener = new MessageCenterView.OnSendMessageListener() {
        public void onSendTextMessage(String text) {
            final TextMessage message = new TextMessage();
            message.setBody(text);
            message.setRead(true);
            message.setCustomData(customData);
            customData = null;
            MessageManager.sendMessage(context, message);
            messageCenterView.post(new Runnable() {
                public void run() {
                    messageCenterView.addMessage(message);
                }
            });
            scrollToBottom();
        }

        public void onSendFileMessage(Uri uri) {
            // First, create the file, and populate some metadata about it.
            final FileMessage message = new FileMessage();
            boolean successful = message.internalCreateStoredImage(context, uri.toString());
            if (successful) {
                message.setRead(true);
                message.setCustomData(customData);
                customData = null;
                // Finally, send out the message.
                MessageManager.sendMessage(context, message);
                messageCenterView.post(new Runnable() {
                    public void run() {
                        messageCenterView.addMessage(message);
                    }
                });
                scrollToBottom();
            } else {
                Log.e("Unable to send file.");
                Toast.makeText(messageCenterView.getContext(), "Unable to send file.", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    };

    messageCenterView = new MessageCenterView((Activity) context, onSendMessagelistener);

    // Remove an existing MessageCenterView and replace it with this, if it exists.
    if (messageCenterView.getParent() != null) {
        ((ViewGroup) messageCenterView.getParent()).removeView(messageCenterView);
    }
    ((Activity) context).setContentView(messageCenterView);

    // Display the messages we already have for starters.
    messageCenterView.setMessages(MessageManager.getMessages(context));

    // This listener will run when messages are retrieved from the server, and will start a new thread to update the view.
    MessageManager.setInternalOnMessagesUpdatedListener(new MessageManager.OnNewMessagesListener() {
        public void onMessagesUpdated() {
            messageCenterView.post(new Runnable() {
                public void run() {
                    List<Message> messages = MessageManager.getMessages(context);
                    messageCenterView.setMessages(messages);
                    scrollToBottom();
                }
            });
        }
    });

    // Change to foreground polling, which polls more often.
    MessagePollingWorker.setMessageCenterInForeground(true);

    // Give the MessageCenterView a callback when a message is sent.
    MessageManager.setSentMessageListener(messageCenterView);

    scrollToBottom();
}

From source file:edu.stanford.mobisocial.dungbeetle.Helpers.java

public static Uri addDynamicGroup(final Context c, final Uri uri) {
    Uri url = Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/dynamic_groups");
    ContentValues values = new ContentValues();
    values.put("uri", uri.toString());
    return c.getContentResolver().insert(url, values);
}

From source file:eu.e43.impeller.Utils.java

public static String getProxyUrl(Context ctx, Account acct, JSONObject obj) {
    if (obj.has("pump_io")) {
        JSONObject pump_io = obj.optJSONObject("pump_io");
        String url = pump_io.optString("proxyURL", null);

        // If the hosts mismatch between the proxyURL and the Account ID, assume we have a
        // "leakage" issue
        Uri uri = Uri.parse(url);/*  w w  w  .  j av a 2 s .  c  o m*/
        Uri userUri = Uri.parse(AccountManager.get(ctx).getUserData(acct, "id"));
        if (!uri.getHost().equalsIgnoreCase(userUri.getHost())) {
            Log.w("Utils.getProxyUrl",
                    "Discarding proxyURL " + url + " due to host mismatch with user " + userUri.toString());
            return null;
        }

        if (url == null || url.length() == 0)
            return null;
        return url;
    } else
        return null;
}

From source file:Main.java

public static File getFromMediaUri(ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;
    if ("file".equals(uri.getScheme())) {
        return new File(uri.getPath());
    } else if ("content".equals(uri.getScheme())) {
        final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
        Cursor cursor = null;/*from w  ww . ja  va  2s.  c  om*/
        try {
            cursor = resolver.query(uri, filePathColumn, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d"))
                        ? cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                        : cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
                if (columnIndex != -1) {
                    String filePath = cursor.getString(columnIndex);
                    if (!TextUtils.isEmpty(filePath)) {
                        return new File(filePath);
                    }
                }
            }
        } catch (SecurityException ignored) {
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }
    return null;
}

From source file:com.chen.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from www .j  a  v a2  s  .  c om*/
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:com.indeema.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///from  www  . j  ava  2 s.c om
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri = null;
    long size;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            if (attachment.mFileName == null) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            html = html.replaceAll(contentIdRe, srcContentUri);
            cv.put(BodyColumns.HTML_CONTENT, html);
            context.getContentResolver().update(ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv,
                    null, null);
        }
    }
}

From source file:Main.java

public static File getFromMediaUri(ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;

    if (SCHEME_FILE.equals(uri.getScheme())) {
        return new File(uri.getPath());
    } else if (SCHEME_CONTENT.equals(uri.getScheme())) {
        final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
        Cursor cursor = null;/*from   w  w  w.ja va 2  s . c om*/
        try {
            cursor = resolver.query(uri, filePathColumn, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d"))
                        ? cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                        : cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
                // Picasa image on newer devices with Honeycomb and up
                if (columnIndex != -1) {
                    String filePath = cursor.getString(columnIndex);
                    if (!TextUtils.isEmpty(filePath)) {
                        return new File(filePath);
                    }
                }
            }
        } catch (SecurityException ignored) {
            // Nothing we can do
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }
    return null;
}