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.mio.jrdv.sunshine.FetchWeatherTask.java

@Override
protected String[] 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 w  w.  jav  a2  s .co 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();

        //ESTO DA
        //http://api.openweathermap.org/data/2.5/forecast/daily?q=seville&mode=json&units=metric&cnt=14

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

        //Y ESTO LO MISMO

        //http://api.openweathermap.org/data/2.5/forecast/daily?q=seville&mode=json&units=metric&cnt=14

        // 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 {
        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.google.ytd.SubmitActivity.java

private File getFileFromUri(Uri uri) throws IOException {
    Cursor cursor = managedQuery(uri, null, null, null, null);
    if (cursor.getCount() == 0) {
        throw new IOException(String.format("cannot find data from %s", uri.toString()));
    } else {//from   w w  w  .  j  a  v  a2s  .c  o m
        cursor.moveToFirst();
    }

    String filePath = cursor.getString(cursor.getColumnIndex(Video.VideoColumns.DATA));

    File file = new File(filePath);
    cursor.close();
    return file;
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from  w  ww  .  j av  a 2 s .c  o m*/
    String locationQuery = WeatherUtil.getPreferredLocation(getContext());

    // 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 available 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, locationQuery)
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY).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;
        }
        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;
        }
        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.
    } 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;
}

From source file:com.hackensack.umc.activity.ProfileSelfiewithCropActivity.java

private void doCrop(Uri uri) {
    Intent intent = new Intent(this, CropImage.class);
    try {//from  w ww .j  a v a  2s.c  o  m
        intent.putExtra("image-path", uri.toString());
        intent.putExtra(Constant.SELECTED_IMAGE_VIEW, selectedImageView);
        intent.putExtra("scale", true);
        startActivityForResult(intent, 123);
    } catch (NullPointerException e) {

    }

}

From source file:com.swater.meimeng.activity.oomimg.ImageCache.java

/**
 * Blocking call to download an image. The image is placed directly into the disk cache at the
 * given key.//  ww w  .  j a va 2s  .c o  m
 *
 * @param uri
 *            the location of the image
 * @return a decoded bitmap
 * @throws org.apache.http.client.ClientProtocolException
 *             if the HTTP response code wasn't 200 or any other HTTP errors
 * @throws java.io.IOException
 */
protected void downloadImage(String key, Uri uri) throws ClientProtocolException, IOException {
    if (DEBUG) {
        Log.d(TAG, "downloadImage(" + key + ", " + uri + ")");
    }
    if (USE_APACHE_NC) {
        final HttpGet get = new HttpGet(uri.toString());
        final HttpParams params = get.getParams();
        params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);

        final HttpResponse hr = hc.execute(get);
        final StatusLine hs = hr.getStatusLine();
        if (hs.getStatusCode() != 200) {
            throw new HttpResponseException(hs.getStatusCode(), hs.getReasonPhrase());
        }

        final HttpEntity ent = hr.getEntity();

        // TODO I think this means that the source file must be a jpeg. fix this.
        try {

            putRaw(key, ent.getContent());
            if (DEBUG) {
                Log.d(TAG, "source file of " + uri + " saved to disk cache at location "
                        + getFile(key).getAbsolutePath());
            }
        } finally {
            ent.consumeContent();
        }
    } else {
        final URLConnection con = new URL(uri.toString()).openConnection();
        putRaw(key, con.getInputStream());
        if (DEBUG) {
            Log.d(TAG, "source file of " + uri + " saved to disk cache at location "
                    + getFile(key).getAbsolutePath());
        }
    }

}

From source file:com.github.gorbin.asne.instagram.InstagramSocialNetwork.java

/**
 * Overrided for Instagram support/* w  ww  . j  av a2 s. co m*/
 * @param requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
 * @param resultCode The integer result code returned by the child activity through its setResult().
 * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    int sanitizedRequestCode = requestCode & 0xFFFF;
    if (sanitizedRequestCode != REQUEST_AUTH)
        return;
    super.onActivityResult(requestCode, resultCode, data);

    Uri uri = data != null ? data.getData() : null;

    if (uri != null && uri.toString().startsWith(mRedirectURL)) {
        String parts[] = uri.toString().split("=");
        String verifier = parts[1];
        RequestLogin2AsyncTask requestLogin2AsyncTask = new RequestLogin2AsyncTask();
        mRequests.put(REQUEST_LOGIN2, requestLogin2AsyncTask);
        Bundle args = new Bundle();
        args.putString(RequestLogin2AsyncTask.PARAM_VERIFIER, verifier);
        requestLogin2AsyncTask.execute(args);
    } else {
        if (mLocalListeners.get(REQUEST_LOGIN) != null) {
            mLocalListeners.get(REQUEST_LOGIN).onError(getID(), REQUEST_LOGIN, "incorrect URI returned: " + uri,
                    null);
            mLocalListeners.remove(REQUEST_LOGIN);
        }
    }
}

From source file:com.dvdprime.mobile.android.ui.DocumentViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_Sherlock_Light);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    super.onCreate(savedInstanceState);

    // Initialize WebView
    mWebView = new DpWebView(this);
    mWebView.setId(mWebView.hashCode());
    mWebView.setOnCreateContextMenuListener(this);

    // Initialize Ad.
    mAdManager = new DpAdManager();
    mAdManager.onCreate(this);

    mLayout = new RelativeLayout(this);
    mAdView = new DpAdViewCore(this);
    mAdView.setId(mAdView.hashCode());//from   ww w  . j  a  va  2 s  . c  o m

    RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);
    layoutParams1.addRule(RelativeLayout.ABOVE, mAdView.getId());
    mLayout.addView(mWebView, layoutParams1);

    RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    mLayout.addView(mAdView, layoutParams2);
    mAdManager.bindCoreView(mAdView);

    setContentView(mLayout);

    // Initialize pull to refresh
    mPullToRefreshAttacher = PullToRefreshAttacher.get(this);
    mPullToRefreshAttacher.addRefreshableView(mWebView, this);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        mLayout.findViewById(mAdView.getId()).setVisibility(View.GONE);
    }
    this.overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
    this.mActivity = this;

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        try {
            index = bundle.getInt("index", 0);
            Document doc = (Document) DpApp.getDocumentList().get(this.index);
            getSupportActionBar().setTitle(doc.getUserName());
            getSupportActionBar().setSubtitle(doc.getTitle());
            mUrl = Config.getAbsoluteUrl("/bbs" + doc.getUrl());
        } catch (Exception e) {
        }
    }
    Uri uri = getIntent().getData();
    if (uri != null) {
        this.mUrl = uri.toString();
        if (getIntent().getExtras().getString("targetKey") != null) {
            mTargetKey = getIntent().getExtras().getString("targetKey");
        }
    }
    if (StringUtil.isBlank(this.mUrl)) {
        finish();
    }
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayUseLogoEnabled(true);

    // Initialize EventBus
    EventBusProvider.getInstance().register(this, String.class, new Class[] { Refresh.class });

    // Request Document View
    StringRequest req = new StringRequest(0, this.mUrl, createReqSuccessListener(), createReqErrorListener());
    req.setTag(this.TAG);
    DpApp.getRequestQueue().add(req);

    // Initialize Google Analytics
    EasyTracker.getInstance().setContext(this.mActivity);
    EasyTracker.getTracker().sendView("DocView");
    LogUtil.LOGD("Tracker", "DocView");
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*from ww w .  j  a  v  a2s  .c o  m*/
    if (intent != null) {
        String action = intent.getAction();
        if ((action != null) && action.equals(Intent.ACTION_SEND)) {
            if (intent.hasExtra(Intent.EXTRA_STREAM))
                getPhoto((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
            if (intent.hasExtra(Intent.EXTRA_TEXT)) {
                final String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                mMessage.setText(text);
                mCount.setText(Integer.toString(text.length()));
            }
            chooseAccounts();
        } else {
            Uri data = intent.getData();
            if ((data != null) && data.toString().contains(Accounts.getContentUri(this).toString())) {
                // default to the account passed in, but allow selecting additional accounts
                Cursor account = this.getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID, Accounts.SERVICE }, Accounts._ID + "=?",
                        new String[] { data.getLastPathSegment() }, null);
                if (account.moveToFirst())
                    mAccountsService.put(account.getLong(0), account.getInt(1));
                account.close();
            } else if (intent.hasExtra(Widgets.INSTANT_UPLOAD)) {
                // check if a photo path was passed and prompt user to select the account
                setPhoto(intent.getStringExtra(Widgets.INSTANT_UPLOAD));
                chooseAccounts();
            }
        }
    }
}

From source file:com.ximai.savingsmore.save.activity.AddGoodsAcitivyt.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode != RESULT_OK) {
        return;//from www . j av a  2  s.c o m
    } else if (requestCode == PICK_FROM_CAMERA || requestCode == PICK_FROM_IMAGE) {

        Uri uri = null;
        if (null != intent && intent.getData() != null) {
            uri = intent.getData();
        } else {
            String fileName = PreferencesUtils.getString(this, "tempName");
            uri = Uri.fromFile(new File(FileSystem.getCachesDir(this, true).getAbsolutePath(), fileName));
        }

        if (uri != null) {
            cropImage(uri, CROP_PHOTO_CODE);
        }
    } else if (requestCode == CROP_PHOTO_CODE) {
        Uri photoUri = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
        try {
            upLoadImage(new File((new URI(photoUri.toString()))), "BusinessLicense");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        //addImage(imagePath);

    }
}

From source file:com.bt.download.android.gui.Librarian.java

public FileDescriptor getFileDescriptor(Uri uri) {
    FileDescriptor fd = null;//from  w w w .ja v  a 2s.c om
    try {
        if (uri != null) {
            if (uri.toString().startsWith("file://")) {
                fd = getFileDescriptor(new File(uri.getPath()));
            } else {
                TableFetcher fetcher = TableFetchers.getFetcher(uri);

                fd = new FileDescriptor();
                fd.fileType = fetcher.getFileType();
                fd.id = Integer.valueOf(uri.getLastPathSegment());
            }
        }
    } catch (Throwable e) {
        fd = null;
        // sometimes uri.getLastPathSegment() is not an integer
        e.printStackTrace();
    }
    return fd;
}