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.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java

@Override
protected Void doInBackground(String... params) {

    // Verify size of params.
    if (params.length == 0) {
        return null;
    }/* w  w w.j  a v  a 2s.c om*/

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    try {
        // Construct the URL for the discover movie query
        // http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=[YOUR API KEY]
        final String FORECAST_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
        final String QUERY_PARAM_SORT = "sort_by";
        final String QUERY_PARAM_API_KEY = "api_key";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                .appendQueryParameter(QUERY_PARAM_SORT, params[0])
                .appendQueryParameter(QUERY_PARAM_API_KEY, params[1]).build();

        URL url = new URL(builtUri.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        //urlConnection.setConnectTimeout(5000);
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        String movieJsonStr = buffer.toString();
        getMovieDataFromJson(movieJsonStr);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        return null;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }
    return null;

}

From source file:com.barcamppenang2014.tabfragment.ProfileFragment.java

License:asdf

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    Log.d("yc", "call onActivityResult in profilefragment ");
    if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        // Recyle unused bitmaps
        /*//from w  w  w  .  j a v  a2  s  . com
         * if (bitmap != null) { bitmap.recycle(); }
         */
        Uri uri = data.getData();
        uriStr = uri.toString();
        // save picUri to sharedpreference
        SharedPreferences sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES",
                Context.MODE_PRIVATE);
        Editor editor = sharedpreferences.edit();
        // picUri could be 'none' or a valid picUri
        editor.putString("picuri", uriStr);
        editor.commit();

        try {
            URIToBitmap(uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
        MainActivity._tempFragment = null;
    }
}

From source file:com.commontime.plugin.notification.notification.Options.java

/**
 * Parse asset URIs.//w  w w. j  a v a 2  s.c om
 */
private void parseAssets() {

    if (options.has("iconUri"))
        return;

    Uri iconUri = assets.parse(options.optString("icon", "icon"));
    Uri soundUri = assets.parseSound(options.optString("sound", null));

    try {
        options.put("iconUri", iconUri.toString());
        options.put("soundUri", soundUri.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:me.xingrz.prox.tcp.TcpProxySession.java

public void accept(SocketChannel localChannel) {
    accepted = true;//from  w  ww .j a v a2s . co m

    incomingTunnel = new IncomingTunnel(selector, localChannel, String.format("%08x", hashCode())) {
        @Override
        protected void onParsedHost(String host) {
            host = lookup(host);

            if (host == null) {
                Uri lastUsed = AutoConfigManager.getInstance().getLastUsedProxy();
                if (Blacklist.contains(getRemoteAddress()) && lastUsed != null) {
                    logger.v("Remote %s is in black list, using last used proxy %s",
                            getRemoteAddress().getHostAddress(), lastUsed.toString());
                    setDestination(lastUsed);
                }

                enqueue();
            } else {
                DnsReverseCache.put(getRemoteAddress(), host);
                AutoConfigManager.getInstance().lookup(host, new AutoConfigManager.ProxyLookupCallback() {
                    @Override
                    public void onProxyLookup(Uri proxy) {
                        if (proxy != null) {
                            setDestination(proxy);
                        }

                        enqueue();
                    }
                });
            }
        }
    };

    logger.v("Established incoming tunnel local:%d <=> proxy:%d", getSourcePort(),
            incomingTunnel.socket().getLocalPort());

    try {
        outgoingTunnel = new OutgoingTunnel(selector, String.format("%08x", hashCode()));
    } catch (IOException e) {
        logger.w(e, "Failed to issue outgoing tunnel, close");
        IOUtils.closeQuietly(this);
        return;
    }

    ProxVpnService.getInstance().protect(outgoingTunnel.socket());

    logger.v("Established outgoing tunnel proxy:%d -> internet", outgoingTunnel.socket().getLocalPort());

    incomingTunnel.setBrother(outgoingTunnel);
    outgoingTunnel.setBrother(incomingTunnel);

    incomingTunnel.beginReceiving();
}

From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java

/**
 * //from  www . j a  v  a 2 s. c  o m
 * @return a map that contains objects with the following keys:
 * 
 *         delete - the url used to delete the uploaded image (null if
 *         error).
 * 
 *         original - the url to the uploaded image (null if error) The map
 *         is null if error
 */
private Map<String, String> handleSendIntent(final Intent intent) {
    Log.i(this.getClass().getName(), "in handleResponse()");

    Log.d(this.getClass().getName(), intent.toString());
    final Bundle extras = intent.getExtras();
    try {
        //upload a new image
        if (Intent.ACTION_SEND.equals(intent.getAction()) && (extras != null)
                && extras.containsKey(Intent.EXTRA_STREAM)) {

            final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
            if (uri != null) {
                Log.d(this.getClass().getName(), uri.toString());
                imageLocation = uri;
                final String jsonOutput = readPictureDataAndUpload(uri);
                return parseJSONResponse(jsonOutput);
            }
            Log.e(this.getClass().getName(), "URI null");
        }
    } catch (final Exception e) {
        Log.e(this.getClass().getName(), "Completely unexpected error", e);
    }
    return null;
}

From source file:jp.mixi.android.sdk.MixiDialog.java

private WebView setUpWebView(WebView webView) {
    Log.v(TAG, "setwebview");
    webView.getSettings().setUserAgentString(Constants.USER_AGENT);
    webView.setVerticalScrollBarEnabled(false);
    webView.setHorizontalScrollBarEnabled(false);
    webView.setWebViewClient(new MixiWebviewClient());

    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new JsHandler(), "mixi");

    String token = mParams.get("oauth_token");
    int sdkInt = Integer.valueOf(Build.VERSION.SDK);
    // android2.1
    if (sdkInt < Constants.SUPPORTED_SDK_VERSION) {
        Uri uri = Uri.parse(mUrl);
        if (token != null) {
            Builder builder = uri.buildUpon();
            builder.appendQueryParameter("oauth_token", token);
            uri = builder.build();/*from   w  w  w. j a  v  a2s  . co m*/
        }
        webView.loadUrl(uri.toString());
    } else {
        HashMap<String, String> extraHeaders = new HashMap<String, String>();
        if (token != null) {
            extraHeaders.put("Authorization", "OAuth " + token);
        }
        webView.loadUrl(mUrl, extraHeaders);
    }

    return webView;
}

From source file:com.facebook.stetho.inspector.ChromeDiscoveryHandler.java

private void handlePageList(HttpResponse response) throws JSONException, UnsupportedEncodingException {
    if (mPageListResponse == null) {
        JSONArray reply = new JSONArray();
        JSONObject page = new JSONObject();
        page.put("type", "app");
        page.put("title", makeTitle());
        page.put("id", PAGE_ID);
        page.put("description", "");

        page.put("webSocketDebuggerUrl", "ws://" + mInspectorPath);
        Uri chromeFrontendUrl = new Uri.Builder().scheme("http")
                .authority("chrome-devtools-frontend.appspot.com").appendEncodedPath("serve_rev")
                .appendEncodedPath(WEBKIT_REV).appendEncodedPath("devtools.html")
                .appendQueryParameter("ws", mInspectorPath).build();
        page.put("devtoolsFrontendUrl", chromeFrontendUrl.toString());

        reply.put(page);/*from w w  w. ja  v  a  2 s. c o m*/
        mPageListResponse = createStringEntity("application/json", reply.toString());
    }
    setSuccessfulResponse(response, mPageListResponse);
}

From source file:de.sitewaerts.cordova.documentviewer.DocumentViewerPlugin.java

private File getFile(String fileArg) throws JSONException {
    String filePath;// w w w . j a va  2  s  .  c o  m
    try {
        CordovaResourceApi resourceApi = webView.getResourceApi();
        Uri fileUri = resourceApi.remapUri(Uri.parse(fileArg));
        filePath = this.stripFileProtocol(fileUri.toString());
    } catch (Exception e) {
        filePath = fileArg;
    }
    return new File(filePath);
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

/**
 * //from w  w w.j  a  va  2  s  .co m
 * @return a map that contains objects with the following keys:
 * 
 *         delete - the url used to delete the uploaded image (null if
 *         error).
 * 
 *         original - the url to the uploaded image (null if error) The map
 *         is null if error
 */
private Map<String, String> handleSendIntent(final Intent intent) {
    Log.i(this.getClass().getName(), "in handleResponse()");

    Log.d(this.getClass().getName(), intent.toString());
    final Bundle extras = intent.getExtras();
    try {
        //upload a new image
        if (Intent.ACTION_SEND.equals(intent.getAction()) && (extras != null)
                && extras.containsKey(Intent.EXTRA_STREAM)) {

            final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
            if (uri != null) {
                Log.d(this.getClass().getName(), uri.toString());
                // store uri so we can create the thumbnail if we succeed
                imageLocation = uri;
                final String jsonOutput = readPictureDataAndUpload(uri);
                return parseJSONResponse(jsonOutput);
            }
            Log.e(this.getClass().getName(), "URI null");
        }
    } catch (final Exception e) {
        Log.e(this.getClass().getName(), "Completely unexpected error", e);
    }
    return null;
}