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.adamhurwitz.android.popularmovies.service.ReviewService.java

@Override
protected void onHandleIntent(Intent intent) {
    String[] reviewArray = intent.getStringArrayExtra("REVIEW_QUERY");

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

    // Will contain the raw JSON response as a string.
    String jsonResponse = null;/* w  w w.j av a  2  s .com*/

    try {
        // Construct the URL to fetch data from and make the connection.
        Uri builtUri = Uri.parse(BASE_URL + reviewArray[0] + "/reviews").buildUpon()
                .appendQueryParameter(KEY_PARAMETER, KEY_CODE).build();
        URL url = new URL(builtUri.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // See if the input stream is not null and a connection could be made. If it is null, do
        // not process any further.
        InputStream inputStream = urlConnection.getInputStream();
        StringBuilder buffer = new StringBuilder();
        if (inputStream == null) {
            return;
        }

        // Read the input stream to see if any valid response was give.
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            // Add new to make debugging easier.
            buffer.append(line).append("\n");
        }
        if (buffer.length() == 0) {
            // If the stream is empty, do not process any further.
            return;
        }

        jsonResponse = buffer.toString();

    } catch (IOException e) {
        // If there was no valid Google doodle data returned, there is no point in attempting to
        // parse it.
        Log.e(LOG_TAG, "Error, IOException.", e);
        return;
    } finally {
        // Make sure to close the connection and the reader no matter what.
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream ", e);
            }
        }
    }

    try {
        parseJSONResponse(jsonResponse, reviewArray[1]);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // Any other case that gets here is an error that was not caught, so return null.
    return;
}

From source file:org.mobisocial.corral.ContentCorral.java

private static void downloadFile(File storageDir, Uri page, String localPath) throws IOException {
    URL url = new URL(page.toString());
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());

    File outFile = new File(storageDir, localPath);
    outFile.getParentFile().mkdirs();/*from w ww.  j a v a  2 s  .c o  m*/
    FileOutputStream outStream = new FileOutputStream(outFile);

    byte[] buffer = new byte[2048];
    int readLength;
    while ((readLength = inputStream.read(buffer)) > 0) {
        outStream.write(buffer, 0, readLength);
    }

    outStream.close();
    inputStream.close();
}

From source file:com.marpies.ane.firebase.auth.utils.FirebaseAuthHelper.java

private String getJSONFromUserInfo(UserInfo userInfo) {
    JSONObject json = new JSONObject();
    try {//from   w  w  w.  j ava 2  s. c  o  m
        String providerId = userInfo.getProviderId();
        if (providerId != null) {
            json.put("providerId", providerId);
        }
        String uid = userInfo.getUid();
        if (uid != null) {
            json.put("uid", uid);
        }
        String displayName = userInfo.getDisplayName();
        if (displayName != null) {
            json.put("displayName", displayName);
        }
        String email = userInfo.getEmail();
        if (email != null) {
            json.put("email", email);
        }
        Uri photoURL = userInfo.getPhotoUrl();
        if (photoURL != null) {
            json.put("photoURL", photoURL.toString());
        }
        return json.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.juick.android.Utils.java

public static void setupWebView(final WebView wv, String content) {
    try {//from  www  .  j  a v a 2s .  c  o  m
        if (skipWeb)
            return;
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(wv.getContext());
        File file = new File(wv.getContext().getCacheDir(), "temp.html");
        String PREFIX = "#prefs.checked.";
        while (true) {
            int ix = content.indexOf(PREFIX);
            if (ix == -1)
                break;
            int ix2 = content.indexOf("#", ix + 1);
            if (ix2 == -1)
                break;
            String key = content.substring(ix + PREFIX.length(), ix2);
            boolean def = false;
            if (key.endsWith("!")) {
                def = true;
                key = key.substring(0, key.length() - 1);
            }
            boolean checked = sp.getBoolean(key, def);
            content = content.substring(0, ix) + (checked ? "checked" : "") + content.substring(ix2 + 1);
        }
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(content);
        fileWriter.close();
        wv.getSettings().setJavaScriptEnabled(true);
        //            wv.getSettings().setBlockNetworkImage(false);
        //            wv.getSettings().setBlockNetworkLoads(false);
        wv.getSettings().setLoadsImagesAutomatically(true);
        Uri uri = Uri.fromFile(file);
        wv.addJavascriptInterface(new Object() {
            public void onFormData(String str) {
                wv.setTag(str);
            }
        }, "EXT");
        wv.loadUrl(uri.toString());
    } catch (IOException e) {
        //
    }

}

From source file:com.krayzk9s.imgurholo.services.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    final NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    ids = intent.getParcelableArrayListExtra("ids");
    albumName = "/";
    downloaded = 0;//ww  w . j  a v a 2  s .c  o m
    if (ids.size() > 0) {
        albumName += intent.getStringExtra("albumName") + "/";
        File myDirectory = new File(
                android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                albumName);
        if (!myDirectory.exists()) {
            myDirectory.mkdirs();
        }
    }
    for (int i = 0; i < ids.size(); i++) {
        try {
            final String type = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE)
                    .split("/")[1];
            final String id = ids.get(i).getJSONObject().getString("id");
            final String link = ids.get(i).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK);
            Log.d("data", ids.get(i).getJSONObject().toString());
            Log.d(ImgurHoloActivity.IMAGE_DATA_TYPE,
                    ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_TYPE).split("/")[1]);
            Log.d("id", ids.get(i).getJSONObject().getString("id"));
            Log.d(ImgurHoloActivity.IMAGE_DATA_LINK,
                    ids.get(0).getJSONObject().getString(ImgurHoloActivity.IMAGE_DATA_LINK));
            final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
            notificationBuilder.setContentTitle(getString(R.string.picture_download))
                    .setContentText(getString(R.string.download_in_progress))
                    .setSmallIcon(R.drawable.icon_desaturated);
            Ion.with(getApplicationContext(), link).progress(new ProgressCallback() {
                @Override
                public void onProgress(int i, int i2) {
                    notificationBuilder.setProgress(i2, i, false);
                }
            }).write(new File(
                    android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                            + albumName + id + "." + type))
                    .setCallback(new FutureCallback<File>() {
                        @Override
                        public void onCompleted(Exception e, File file) {
                            if (file == null)
                                return;
                            downloaded += 1;
                            if (downloaded == ids.size()) {
                                NotificationCompat.Builder notificationComplete = new NotificationCompat.Builder(
                                        getApplicationContext());
                                if (ids.size() == 1) {
                                    Intent viewImageIntent = new Intent(Intent.ACTION_VIEW);
                                    viewImageIntent.setDataAndType(Uri.fromFile(file), "image/*");
                                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                                    shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                                    shareIntent.setType("image/*");
                                    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                                    PendingIntent viewImagePendingIntent = PendingIntent.getActivity(
                                            getApplicationContext(), (int) System.currentTimeMillis(),
                                            viewImageIntent, 0);
                                    PendingIntent sharePendingIntent = PendingIntent.getActivity(
                                            getApplicationContext(), (int) System.currentTimeMillis(),
                                            shareIntent, 0);
                                    notificationComplete.setContentTitle(getString(R.string.download_complete))
                                            .setSmallIcon(R.drawable.icon_desaturated)
                                            .setContentText(String.format(getString(R.string.download_progress),
                                                    downloaded))
                                            .setContentIntent(viewImagePendingIntent)
                                            .addAction(R.drawable.dark_social_share, getString(R.string.share),
                                                    sharePendingIntent);
                                } else {
                                    Intent i = new Intent(Intent.ACTION_PICK);
                                    i.setDataAndType(
                                            Uri.fromFile(new File(
                                                    android.os.Environment.getExternalStoragePublicDirectory(
                                                            Environment.DIRECTORY_PICTURES) + albumName)),
                                            "image/*");
                                    PendingIntent viewImagePendingIntent = PendingIntent.getActivity(
                                            getApplicationContext(), (int) System.currentTimeMillis(), i, 0);
                                    notificationComplete.setContentTitle(getString(R.string.download_complete))
                                            .setSmallIcon(R.drawable.icon_desaturated).setContentText(String
                                                    .format(getString(R.string.download_progress), downloaded))
                                            .setContentIntent(viewImagePendingIntent);
                                }
                                notificationManager.cancel(0);
                                notificationManager.cancel(1);
                                notificationManager.notify(1, notificationComplete.build());
                            }
                            MediaScannerConnection.scanFile(getApplicationContext(),
                                    new String[] { android.os.Environment.getExternalStoragePublicDirectory(
                                            Environment.DIRECTORY_PICTURES) + albumName + id + "." + type },
                                    null, new MediaScannerConnection.OnScanCompletedListener() {
                                        @Override
                                        public void onScanCompleted(final String path, final Uri uri) {
                                            Log.i("Scanning", String.format("Scanned path %s -> URI = %s", path,
                                                    uri.toString()));
                                        }
                                    });
                        }
                    });
            notificationManager.notify(0, notificationBuilder.build());
        } catch (JSONException e) {
            Log.e("Error!", e.toString());
        }
    }
}

From source file:com.crowflying.buildwatch.ConfigurationActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EasyTracker.getInstance().setContext(getApplicationContext());
    tracker = EasyTracker.getTracker();//w w  w  . j a  v  a  2s  .co  m
    Uri data = getIntent().getData();
    if (data != null && data.toString().contains("server")) {
        addPreferencesFromResource(R.xml.server_preferences);
    } else {
        addPreferencesFromResource(R.xml.preferences);
    }
}

From source file:com.sudhirkhanger.app.popularmovies.FetchTasks.FetchReviews.java

@Override
protected ArrayList<Review> doInBackground(String... params) {

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

    // Will contain the raw JSON response as a string.
    String reviewJsonStr = null;/*from   www  . j  a v a2 s.co m*/

    try {
        // Construct the URL for the MovieDB query

        final String MDB_BASE_URL = "http://api.themoviedb.org/3/movie/";
        final String PATH_REVIEWS = "reviews";
        final String QUERY_API_KEY = "api_key";

        // http://api.themoviedb.org/3/movie/{movie_id}/reviews?api_key={API_KEY}

        Uri builtUri = Uri.parse(MDB_BASE_URL).buildUpon().appendPath(params[0]).appendPath(PATH_REVIEWS)
                .appendQueryParameter(QUERY_API_KEY, BuildConfig.THE_MOVIE_DB_API_KEY).build();

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

        Log.d(LOG_TAG, url.toString());

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

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            reviewJsonStr = 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.
            reviewJsonStr = null;
        }
        reviewJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attempting
        // to parse it.
        reviewJsonStr = null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        return getReviewsFromJson(reviewJsonStr);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    return null;
}

From source file:com.sudhirkhanger.app.popularmovies.FetchTasks.FetchTrailers.java

@Override
protected ArrayList<Trailer> doInBackground(String... params) {

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

    // Will contain the raw JSON response as a string.
    String trailerJsonStr = null;

    try {//from www.j  a va2  s . c  om
        // Construct the URL for the MovieDB query

        final String MDB_BASE_URL = "http://api.themoviedb.org/3/movie/";
        final String PATH_VIDEO = "videos";
        final String QUERY_API_KEY = "api_key";

        // http://api.themoviedb.org/3/movie/209112/videos?api_key={API_KEY}

        Uri builtUri = Uri.parse(MDB_BASE_URL).buildUpon().appendPath(params[0]).appendPath(PATH_VIDEO)
                .appendQueryParameter(QUERY_API_KEY, BuildConfig.THE_MOVIE_DB_API_KEY).build();

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

        Log.d(LOG_TAG, url.toString());

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

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            trailerJsonStr = 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.
            trailerJsonStr = null;
        }
        trailerJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attempting
        // to parse it.
        trailerJsonStr = null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        return getTrailerFromJson(trailerJsonStr);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    return null;
}

From source file:com.adamhurwitz.android.popularmovies.service.MovieDataService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Receive AsyncTask param from MainFragment.java
    String movieQuery = intent.getStringExtra("MOVIE_QUERY");

    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String jsonResponse = null;/* w w  w  .  j a v a2s  .  c  o  m*/

    try {
        // Construct the URL to fetch data from and make the connection.
        Uri builtUri = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(SORT_PARAMETER, movieQuery)
                .appendQueryParameter(KEY_PARAMETER, KEY_CODE).build();
        URL url = new URL(builtUri.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // See if the input stream is not null and a connection could be made. If it is null, do
        // not process any further.
        InputStream inputStream = urlConnection.getInputStream();
        StringBuilder buffer = new StringBuilder();
        if (inputStream == null) {
            return;
        }

        // Read the input stream to see if any valid response was give.
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            // Add new to make debugging easier.
            buffer.append(line).append("\n");
        }
        if (buffer.length() == 0) {
            // If the stream is empty, do not process any further.
            return;
        }

        jsonResponse = buffer.toString();

    } catch (IOException e) {
        // If there was no valid Google doodle data returned, there is no point in attempting to
        // parse it.
        Log.e(LOG_TAG, "Error, IOException.", e);
        return;
    } finally {
        // Make sure to close the connection and the reader no matter what.
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream ", e);
            }
        }
    }

    // If valid data was returned, return the parsed data.
    try {
        Log.i(LOG_TAG, "The Google doodle data that was returned is: " + jsonResponse);
        parseJSONResponse(jsonResponse);
        return;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // Any other case that gets here is an error that was not caught, so return null.
    return;
}

From source file:com.robertszkutak.androidexamples.tumblrexample.TumblrExampleActivity.java

@Override
public void onResume() {
    super.onResume();

    if (auth == false) {
        if (browser == true)
            browser2 = true;/*from w w  w  .  ja va  2  s . c  o m*/

        if (browser == false) {
            browser = true;
            newIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authURL));
            startActivity(newIntent);
        }

        if (browser2 == true) {
            Uri uri = getIntent().getData();
            uripath = uri.toString();

            if (uri != null && uripath.startsWith(OAUTH_CALLBACK_URL)) {
                String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
                try {

                    provider.retrieveAccessToken(consumer, verifier);

                    token = consumer.getToken();
                    secret = consumer.getTokenSecret();

                    final Editor editor = pref.edit();
                    editor.putString("TUMBLR_OAUTH_TOKEN", token);
                    editor.putString("TUMBLR_OAUTH_TOKEN_SECRET", secret);
                    editor.commit();

                    auth = true;
                    loggedin = true;

                } catch (OAuthMessageSignerException e) {
                    e.printStackTrace();
                } catch (OAuthNotAuthorizedException e) {
                    e.printStackTrace();
                } catch (OAuthExpectationFailedException e) {
                    e.printStackTrace();
                } catch (OAuthCommunicationException e) {
                    e.printStackTrace();
                }
            }
        }
    } else {
        setContentView(R.layout.main);

        blogname = (EditText) findViewById(R.id.blogname);
        posttitle = (EditText) findViewById(R.id.posttitle);
        poststring = (EditText) findViewById(R.id.post);
        debugStatus = (TextView) findViewById(R.id.debug_status);
        post = (Button) findViewById(R.id.btn_post);
        loginorout = (Button) findViewById(R.id.loginorout);

        blogname.setText(pref.getString("TUMBLR_BLOG_NAME", ""));

        debug = "Access Token: " + token + "\n\nAccess Token Secret: " + secret;
        debugStatus.setText(debug);

        post.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (isAuthenticated()) {
                    saveBlogName();
                    sendPost();
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "You are not logged into Tumblr",
                            Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });

        loginorout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                LogInOrOut();
            }
        });

        updateLoginStatus();
    }

    if (auth == false && browser2 == true)
        finish();
}