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.appsimobile.appsii.module.weather.ImageDownloadHelper.java

public JSONObject loadPhotoInfo(Context context, String photoId) throws VolleyError {

    Uri uri = Uri.parse("https://api.flickr.com/services/rest/").buildUpon()
            .appendQueryParameter("method", "flickr.photos.getInfo")
            .appendQueryParameter("api_key", FLICKR_API_KEY).appendQueryParameter("photo_id", photoId)
            .appendQueryParameter("format", "json").appendQueryParameter("nojsoncallback", "1").build();

    String url = uri.toString();

    RequestFuture<JSONObject> requestFuture = RequestFuture.newFuture();

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, requestFuture, requestFuture);
    sRequestQueue.add(request);//  w w w .  j a v a  2  s .c  om
    return getResult(requestFuture);
}

From source file:com.example.dhrumil.sunshine.app.FetchWeatherTask.java

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

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }// ww w  .  j  a va2  s.  c  o m
    String locationQuery = params[0];

    // 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 forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.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.
            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;
        }
        forecastJsonStr = buffer.toString();
        getWeatherDataFromJson(forecastJsonStr, locationQuery);
    } 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.
        //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);
            }
        }
    }

    //        try {
    //            return getWeatherDataFromJson(forecastJsonStr, locationQuery);
    //        } catch (JSONException e) {
    //            Log.e(LOG_TAG, e.getMessage(), e);
    //            e.printStackTrace();
    //        }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.iyedb.sunshine.FetchWeatherTask.java

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

    Log.d(LOG_TAG, "in doInBackground");

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }//ww  w. j av  a 2 s.c  om
    String locationParam = params[0];

    Log.d(LOG_TAG, "getting weather data for " + locationParam);

    // 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 forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.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.
            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;
        }
        forecastJsonStr = 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 attemping
        // to parse it.
        return 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 {

        getWeatherDataFromJson(forecastJsonStr, numDays, locationParam);

        if (DEBUG) {
            Cursor cursor = mContext
                    .getContentResolver().query(
                            WeatherEntry.CONTENT_URI, new String[] { WeatherEntry._ID,
                                    WeatherEntry.COLUMN_LOC_KEY, WeatherEntry.COLUMN_WEATHER_ID },
                            null, null, null);

            Log.d(LOG_TAG, "Weather table contents:");
            while (cursor.moveToNext()) {

                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cursor, resultValues);

                StringBuilder stringBuilder = new StringBuilder();
                for (String key : resultValues.keySet()) {
                    stringBuilder.append(key).append(':').append(resultValues.getAsString(key)).append('|');

                }
                Log.v(LOG_TAG, stringBuilder.toString());
            }

            Cursor cursorLoc = mContext.getContentResolver()
                    .query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID,
                            LocationEntry.COLUMN_LOCATION_SETTING, LocationEntry.COLUMN_CITY_NAME }, null, null,
                            null);

            Log.d(LOG_TAG, "Location table contents:");
            while (cursorLoc.moveToNext()) {

                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cursorLoc, resultValues);

                StringBuilder stringBuilder = new StringBuilder();
                for (String key : resultValues.keySet()) {
                    stringBuilder.append(key).append(':').append(resultValues.getAsString(key)).append('|');

                }
                Log.v(LOG_TAG, stringBuilder.toString());
            }
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.dileepindia.cordova.sms.SMSPlugin.java

protected void createContentObserver()

{
    Context ctx = this.cordova.getActivity();

    this.mObserver = new ContentObserver(new Handler()) {

        public void onChange(boolean selfChange) {
            onChange(selfChange, null);//from   w w w  .j  a v a 2s . c om
        }

        public void onChange(boolean selfChange, Uri uri) {
            Log.d("SMSPlugin", "onChange, selfChange: " + selfChange + ", uri: " + uri);

            int id = -1;

            if (uri != null) {
                String str = uri.toString();
                if (str.startsWith("content://sms/")) {
                    String box_or_id = str.substring("content://sms/".length());
                    try {
                        id = Integer.parseInt(str);
                        Log.d("SMSPlugin", "sms id: " + id);
                    } catch (NumberFormatException localNumberFormatException) {
                    }
                }
            }

            if (id == -1) {
                uri = Uri.parse("content://sms/inbox");
            }

            ContentResolver resolver = SMSPlugin.this.cordova.getActivity().getContentResolver();
            Cursor cur = resolver.query(uri, null, null, null, "_id desc");
            if (cur != null) {
                int n = cur.getCount();
                Log.d("SMSPlugin", "n = " + n);
                if ((n > 0) && (cur.moveToFirst())) {
                    JSONObject json = SMSPlugin.this.getJsonFromCursor(cur);
                    if (json != null) {
                        SMSPlugin.this.onSMSArrive(json);
                    } else {
                        Log.d("SMSPlugin", "fetch record return null");
                    }
                }
                cur.close();
            }

        }
    };
    ctx.getContentResolver().registerContentObserver(Uri.parse("content://sms/inbox"), true, this.mObserver);
    Log.d("SMSPlugin", "sms inbox observer registered");
}

From source file:com.example.android.wifidirect.DeviceDetailFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    // User has picked an image. Transfer it to group owner i.e peer using
    // FileTransferService.
    Uri uri = data.getData();
    TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
    statusText.setText("Sending: " + uri);
    Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
    Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
    serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
    serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
    serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
            info.groupOwnerAddress.getHostAddress());
    serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
    getActivity().startService(serviceIntent);

}

From source file:org.peterbaldwin.vlcremote.app.PlaybackActivity.java

@Override
protected void onNewIntent(Intent intent) {
    String host = intent.getStringExtra(Intents.EXTRA_REMOTE_HOST);
    if (host != null) {
        int port = intent.getIntExtra(Intents.EXTRA_REMOTE_PORT, 8080);
        String authority = host + ":" + port;
        changeServer(authority);/*from  www .j ava2  s  .c o m*/
    }

    String action = intent.getAction();
    if (Intent.ACTION_VIEW.equals(action) || Intents.ACTION_REMOTE_VIEW.equals(action)
            || Intents.ACTION_VIEW.equals(action)) {
        Uri data = intent.getData();
        if (data != null) {
            changeInput(data.toString());
        }
    } else if (Intent.ACTION_SEARCH.equals(action)) {
        String input = intent.getStringExtra(SearchManager.QUERY);
        changeInput(input);
    }
}

From source file:com.ravi.apps.android.newsbytes.sync.NewsSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from   w  w w. j  a  v  a 2s  . c o m*/
    Log.d(LOG_TAG, getContext().getString(R.string.log_on_perform_sync));

    HttpURLConnection httpURLConnection = null;
    BufferedReader bufferedReader = null;

    try {
        String newsJsonStr = null;

        // Get the news category preference from shared preferences.
        String newsCategoryPreference = Utility.getNewsCategoryPreference(getContext(), null);

        // Set the news section query param value based on preference.
        String newsCategory = null;
        if (newsCategoryPreference.equals(getContext().getString(R.string.pref_news_category_favorites))) {
            // If favorites category is selected, no need to do a sync - simply return.
            return;
        } else if (newsCategoryPreference.equals(getContext().getString(R.string.pref_news_category_world))) {
            newsCategory = NYT_SECTION_WORLD;
        } else if (newsCategoryPreference
                .equals(getContext().getString(R.string.pref_news_category_business))) {
            newsCategory = NYT_SECTION_BUSINESS;
        } else if (newsCategoryPreference
                .equals(getContext().getString(R.string.pref_news_category_technology))) {
            newsCategory = NYT_SECTION_TECHNOLOGY;
        } else if (newsCategoryPreference.equals(getContext().getString(R.string.pref_news_category_health))) {
            newsCategory = NYT_SECTION_HEALTH;
        } else if (newsCategoryPreference.equals(getContext().getString(R.string.pref_news_category_travel))) {
            newsCategory = NYT_SECTION_TRAVEL;
        } else if (newsCategoryPreference.equals(getContext().getString(R.string.pref_news_category_sports))) {
            newsCategory = NYT_SECTION_SPORTS;
        }

        // Build the uri for querying data from NYT api.
        Uri uri = Uri.parse(NYT_BASE_URL + newsCategory + NYT_RESPONSE_FORMAT).buildUpon()
                .appendQueryParameter(NYT_API_KEY_PARAM, NYT_API_KEY).build();

        // Create the url for connecting to NYT server.
        URL url = new URL(uri.toString());
        Log.d(LOG_TAG, url.toString());

        // Create the request to NYT server and open the connection.
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();

        // Read the response input stream into a string buffer.
        InputStream inputStream = httpURLConnection.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }

        // Convert the string buffer to string.
        newsJsonStr = stringBuffer.toString();
        Log.d(LOG_TAG, newsJsonStr);

        // Parse the JSON string and extract the news data.
        getNewsDataFromJson(newsJsonStr);

        // Send a local broadcast informing the widget to refresh it's data.
        Utility.sendDataUpdatedBroadcast(getContext());

        // Send a notification to the user that fresh news updates are now available.
        if (Utility.getNewsNotificationsPreference(getContext(), null)) {
            sendNewsNotification(getContext());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, getContext().getString(R.string.log_on_perform_sync_io_error) + e.getLocalizedMessage());
    } catch (JSONException e) {
        Log.e(LOG_TAG,
                getContext().getString(R.string.log_on_perform_sync_json_error) + e.getLocalizedMessage());
    } finally {
        // Close url connection, if open.
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }

        // Close the buffered reader, if open.
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, getContext().getString(R.string.log_on_perform_sync_io_error)
                        + e.getLocalizedMessage());
            }
        }
    }
    return;
}

From source file:app.com.example.kiran.sunshine.FetchWeatherTask.java

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

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*  w ww.  java2  s.  c  om*/
    String locationQuery = params[0];

    // 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 forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;
    String APIID = "4b50d8a1b95648fd22797a7731706dfe";

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";
        final String APPID_PARAM = "APPID";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                .appendQueryParameter(APPID_PARAM, APIID).build();

        URL url = new URL(builtUri.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.
            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;
        }
        forecastJsonStr = 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 attemping
        // to parse it.
        return 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 {
        getWeatherDataFromJson(forecastJsonStr, locationQuery);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.google.android.dialer.provider.DialerProvider.java

private String executeHttpRequest(Uri uri) throws IOException {
    String charset = null;/*from  ww  w.j  a v a 2 s . c  om*/

    if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
        Log.v("DialerProvider", "executeHttpRequest(" + uri + ")");
    }

    try {
        URLConnection conn = new URL(uri.toString()).openConnection();
        conn.setRequestProperty("User-Agent", mUserAgent);

        InputStream inputStream = conn.getInputStream();
        charset = getCharsetFromContentType(conn.getContentType());

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] buf = new byte[1000];
        while (true) {
            int len = inputStream.read(buf);
            if (len <= 0) {
                break;
            }
            outputStream.write(buf, 0, len);
        }

        inputStream.close();
        outputStream.flush();

        return new String(outputStream.toByteArray(), charset);
    } catch (UnsupportedEncodingException e) {
        Log.w("DialerProvider", "Invalid charset: " + charset, e);
    } catch (IOException e) {
        // TODO: Didn't find anything that goes here in byte-code
    }

    // TODO: Is this appropriate?
    return null;
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

/**
 * ??./* w w w.  ja  v a  2s .c  om*/
 */
private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) {
    if (bitmap != null) {
        bitmap.recycle();
        bitmap = null;
    }

    // Clean up initial camera-written image file.
    String filePath = oldImage.toString();
    if (filePath.startsWith("file://")) {
        filePath = filePath.substring(7);
    }
    (new File(filePath)).delete();

    checkForDuplicateImage(imageType);
    System.gc();
}