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.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java

/**
 * makes the network call to fetch the data and the calls storeJsonMovies
 * @param type Flag for the try of movie to fetch.
 * @return Returns an array of ids of the movies that were inserted
 *//*from w w  w .  j  av a  2  s . com*/
public static int[] fetchMovies(int type, Context context) {
    int[] ids = {};
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    String rawJSON = null;
    String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie";
    final String API_KEY_PARAM = "api_key";

    /*
    example urls
    http://api.themoviedb.org/3/movie/top_rated?api_key=xxxxxxx
    http://api.themoviedb.org/3/movie/popular?api_key=xxxxxxxx
    */
    //TODO build Uri programmatically using APIs
    switch (type) {
    case MOVIES_POPULAR:
        MOVIE_BASE_URL += "/popular" + "?";
        break;
    case MOVIES_TOP_RATED:
        MOVIE_BASE_URL += "/top_rated" + "?";
        break;
    default:
        throw new IllegalArgumentException(
                "Unrecognized id passed as params[0].  Params[0] must be the id for the url.  See static constants of this class");
    }

    try {

        Uri droidUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
                .appendQueryParameter(API_KEY_PARAM, BuildConfig.TMDb_API_KEY).build();

        Log.v(TAG, "URL used: " + droidUri.toString());

        URL url = new URL(droidUri.toString()); //java.net Malformed uri exception

        connection = (HttpURLConnection) url.openConnection(); //java.io.  IO exception
        connection.setRequestMethod("GET"); //java.net.ProtocolException && unnecessary
        connection.connect(); //java.io.IOExecption

        InputStream inputStream = connection.getInputStream(); // java.io.IOException
        StringBuffer stringBuffer = new StringBuffer();

        if (inputStream == null) {
            return ids;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        //Make the string more readable
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuffer.append(line + "\n");
        }

        if (stringBuffer.length() == 0) {
            Log.e(TAG + "doInBackground", "empty string");
            return ids;
        }

        rawJSON = stringBuffer.toString();
        Log.d(TAG + "doInBackground", rawJSON);

        switch (type) {
        case MOVIES_POPULAR:
            ids = storeJsonMovies(rawJSON.toString(), type, context);
            break;
        case MOVIES_TOP_RATED:
            ids = storeJsonMovies(rawJSON.toString(), type, context);
            break;
        }

    } catch (IOException e) {
        Log.e(TAG, "Error ", e);
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(TAG, "Error closing stream", e);
                e.printStackTrace();
            }
        }
    }
    return ids;
}

From source file:Main.java

public static Bitmap downSampleBitmap(Uri uri, Activity act, Boolean needRotate) {
    DisplayMetrics displaymetrics = new DisplayMetrics();
    act.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    Resources r = act.getResources();
    int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics()); // 50: magic num
    int targetWidth = displaymetrics.heightPixels;
    int targetHeight = displaymetrics.widthPixels - px;

    Bitmap resizedBitmap = decodeSampledBitmap(uri, targetWidth, targetHeight, act);
    Bitmap returnBitmap = null;/*from w ww  .j  a v  a2  s.  c o  m*/
    ExifInterface exif;
    try {
        float degree = 0;
        exif = new ExifInterface(uri.toString());
        int orient = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        if (resizedBitmap != null && needRotate) {
            degree = getDegree(orient);
            if (degree != 0) {
                returnBitmap = createRotatedBitmap(resizedBitmap, degree);
            }
            returnBitmap = returnBitmap == null ? resizedBitmap : returnBitmap;
        }
    } catch (IOException e) {
        Log.v(TAG, "not found file at downsample");
        e.printStackTrace();
    }
    return returnBitmap;
}

From source file:org.lol.reddit.fragments.PostListingFragment.java

public static PostListingFragment newInstance(final Uri url, final UUID session,
        final CacheRequest.DownloadType downloadType) {

    final PostListingFragment f = new PostListingFragment();

    final Bundle bundle = new Bundle(4);

    bundle.putString("url", url.toString());
    if (session != null)
        bundle.putString("session", session.toString());
    bundle.putString("downloadType", downloadType.name());

    f.setArguments(bundle);//from   w  ww . j a v  a  2s  .  com

    return f;
}

From source file:air.com.snagfilms.utils.Utils.java

public static Map<String, String> getReferrerMapFromUri(Uri uri) {
    MapBuilder paramMap = new MapBuilder();
    // If no URI, return an empty Map.
    if (uri == null) {
        return paramMap.build();
    }/*from  w  w  w  .  j a v  a  2 s .c  om*/
    // Source is the only required campaign field. No need to continue if
    // not
    // present.
    if (uri.getQueryParameter(AnalyticsAPI.CAMPAIGN_SOURCE_PARAM) != null) {
        // MapBuilder.setCampaignParamsFromUrl parses Google Analytics
        // campaign
        // ("UTM") parameters from a string URL into a Map that can be set
        // on
        // the Tracker.
        paramMap.setCampaignParamsFromUrl(uri.toString());
        // If no source parameter, set authority to source and medium to
        // "referral".
    } else if (uri.getAuthority() != null) {
        paramMap.set(Fields.CAMPAIGN_MEDIUM, "referral");
        paramMap.set(Fields.CAMPAIGN_SOURCE, uri.getAuthority());
    }

    return paramMap.build();
}

From source file:Main.java

/**
 * Unmask the URI and return it/*w  ww. j a v a 2  s . co  m*/
 */
public static Uri unmaskLink(Uri uri, int i) {
    String s = null;
    List pathSegments;
    if (MASK_HOSTS_SEG[i] == null) {
        // The host always masks, no need to determine if it's the right segment
        s = uri.getQueryParameter(MASK_HOSTS_PAR[i]);
    } else {
        // Only a certain segment is used to mask URLs. Determine if this is it.
        pathSegments = uri.getPathSegments();
        if (pathSegments == null)
            return uri;
        // If it is, unmask the URL.
        if (pathSegments.size() > 0 && MASK_HOSTS_SEG[i].equals(pathSegments.get(0)))
            s = uri.getQueryParameter(MASK_HOSTS_PAR[i]);
    }

    if (s == null)
        return uri;

    // Resolve link if it's relative
    try {
        if (!new URI(s).isAbsolute())
            s = new URI(uri.toString()).resolve(s).toString();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    try {
        return Uri.parse(URLDecoder.decode(s, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return uri;
    }
}

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

/**
 * Save the attachment to its final resting place (cache or sd card)
 *//*from   w  w  w .  j  a va  2 s  .c  o m*/
public static long saveAttachment(Context context, InputStream in, Attachment attachment) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    String realUri = null; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD
    long size = 0;

    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_CACHE) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment when attachment destination is cache",
                    "attachment.size:" + attachment.mSize);
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment to storage",
                    "attachment.size:" + attachment.mSize);
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // 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");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
            String exchange = "com.tct.exchange";
            if (exchange.equals(context.getPackageName()) && !PermissionUtil
                    .checkPermissionAndLaunchExplain(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                throw new IOException("Can't save an attachment due to no Storage permission");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
            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();
            realUri = "file://" + absolutePath; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD

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

            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;

            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } 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.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
        if (realUri != null) {
            cv.put(AttachmentColumns.REAL_URI, realUri);
        }
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
    } catch (IOException e) {
        LogUtils.e(Logging.LOG_TAG, e, "Fail to save attachment to storage!");
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        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\"";
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_S
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_S
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_E
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_E
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    return size;
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

public static String getCacheFilenameForUri(Uri uri) {
    StringBuilder filename = new StringBuilder();
    filename.append(uri.getScheme()).append("_").append(uri.getHost()).append("_");
    String encodedPath = uri.getEncodedPath();
    if (!TextUtils.isEmpty(encodedPath)) {
        int length = encodedPath.length();
        if (length > 60) {
            encodedPath = encodedPath.substring(length - 60);
        }/*w ww.ja va  2s  .  c  om*/
        encodedPath = encodedPath.replace('/', '_');
        filename.append(encodedPath).append("_");
    }
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(uri.toString().getBytes("UTF-8"));
        byte[] digest = md.digest();
        for (byte b : digest) {
            if ((0xff & b) < 0x10) {
                filename.append("0").append(Integer.toHexString((0xFF & b)));
            } else {
                filename.append(Integer.toHexString(0xFF & b));
            }
        }
    } catch (NoSuchAlgorithmException e) {
        filename.append(uri.toString().hashCode());
    } catch (UnsupportedEncodingException e) {
        filename.append(uri.toString().hashCode());
    }

    return filename.toString();
}

From source file:Main.java

public static String encodeUrl(String url) {
    Uri uri = Uri.parse(url);

    try {//from   w w  w . ja  v a 2  s.  co m
        Map<String, List<String>> splitQuery = splitQuery(uri);
        StringBuilder encodedQuery = new StringBuilder();
        for (String key : splitQuery.keySet()) {
            for (String value : splitQuery.get(key)) {
                if (encodedQuery.length() > 0) {
                    encodedQuery.append("&");
                }
                encodedQuery.append(key + "=" + URLEncoder.encode(value, "UTF-8"));
            }
        }
        String queryString = encodedQuery != null && encodedQuery.length() > 0 ? "?" + encodedQuery : "";

        URI baseUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, uri.getFragment());
        return baseUri + queryString;
    } catch (UnsupportedEncodingException ignore) {
    } catch (URISyntaxException ignore) {
    }

    return uri.toString();
}

From source file:com.ruesga.rview.misc.ActivityHelper.java

public static void handleUri(Context ctx, Uri uri) {
    try {/*from www.ja  v a2s. c  om*/
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.putExtra(Constants.EXTRA_FORCE_SINGLE_PANEL, true);
        intent.putExtra(Constants.EXTRA_HAS_PARENT, true);
        intent.putExtra(Constants.EXTRA_SOURCE, ctx.getPackageName());
        intent.setPackage(ctx.getPackageName());
        ctx.startActivity(intent);
    } catch (ActivityNotFoundException ex) {
        // Fallback to default browser
        String msg = ctx.getString(R.string.exception_browser_not_found, uri.toString());
        Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject toJSONObjectForWeb(final ShareOpenGraphContent shareOpenGraphContent)
        throws JSONException {
    ShareOpenGraphAction action = shareOpenGraphContent.getAction();

    return OpenGraphJSONUtility.toJSONObject(action, new OpenGraphJSONUtility.PhotoJSONProcessor() {
        @Override/*www .ja v  a  2  s. c o m*/
        public JSONObject toJSONObject(SharePhoto photo) {
            Uri photoUri = photo.getImageUrl();
            JSONObject photoJSONObject = new JSONObject();
            try {
                photoJSONObject.put(NativeProtocol.IMAGE_URL_KEY, photoUri.toString());
            } catch (JSONException e) {
                throw new FacebookException("Unable to attach images", e);
            }
            return photoJSONObject;
        }
    });
}