Example usage for android.net Uri getPath

List of usage examples for android.net Uri getPath

Introduction

In this page you can find the example usage for android.net Uri getPath.

Prototype

@Nullable
public abstract String getPath();

Source Link

Document

Gets the decoded path.

Usage

From source file:in.shick.diode.submit.SubmitLinkActivity.java

/**
 * Enable the UI after user is logged in.
 *//*from  ww  w  . j a  va  2s  .c  om*/
private void start() {
    // Intents can be external (browser share page) or from Reddit is fun.
    String intentAction = getIntent().getAction();
    if (Intent.ACTION_SEND.equals(intentAction)) {
        // Share
        Bundle extras = getIntent().getExtras();
        SubmissionProperties submissionProperties = new SubmissionProperties();

        boolean ignored = defaultExtractProperties(extras, submissionProperties)
                || lastDitchExtractProperties(extras, submissionProperties);

        final EditText submitLinkUrl = (EditText) findViewById(R.id.submit_link_url);
        final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
        final EditText submitLinkTitle = (EditText) findViewById(R.id.submit_link_title);
        final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
        submitLinkUrl.setText(submissionProperties.url);
        submitLinkReddit.setText("");
        submitTextReddit.setText("");
        submitLinkTitle.setText(submissionProperties.title);
        mSubmitUrl = Constants.REDDIT_BASE_URL + "/submit";
    } else {
        String submitPath = null;
        Uri data = getIntent().getData();
        if (data != null && Util.isRedditUri(data))
            submitPath = data.getPath();
        if (submitPath == null)
            submitPath = "/submit";

        // the URL to do HTTP POST to
        mSubmitUrl = Util.absolutePathToURL(submitPath);

        // Put the subreddit in the text field
        final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
        final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
        Matcher m = SUBMIT_PATH_PATTERN.matcher(submitPath);
        if (m.matches()) {
            String subreddit = m.group(1);
            if (StringUtils.isEmpty(subreddit)) {
                submitLinkReddit.setText("");
                submitTextReddit.setText("");
            } else {
                submitLinkReddit.setText(subreddit);
                submitTextReddit.setText(subreddit);
            }
        }
    }

    final Button submitLinkButton = (Button) findViewById(R.id.submit_link_button);
    submitLinkButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (validateLinkForm()) {
                final EditText submitLinkTitle = (EditText) findViewById(R.id.submit_link_title);
                final EditText submitLinkUrl = (EditText) findViewById(R.id.submit_link_url);
                final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
                final EditText submitLinkCaptcha = (EditText) findViewById(R.id.submit_link_captcha);
                new SubmitLinkTask(submitLinkTitle.getText().toString(), submitLinkUrl.getText().toString(),
                        submitLinkReddit.getText().toString(), Constants.SUBMIT_KIND_LINK,
                        submitLinkCaptcha.getText().toString()).execute();
            }
        }
    });
    final Button submitTextButton = (Button) findViewById(R.id.submit_text_button);
    submitTextButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (validateTextForm()) {
                final EditText submitTextTitle = (EditText) findViewById(R.id.submit_text_title);
                final EditText submitTextText = (EditText) findViewById(R.id.submit_text_text);
                final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
                final EditText submitTextCaptcha = (EditText) findViewById(R.id.submit_text_captcha);
                new SubmitLinkTask(submitTextTitle.getText().toString(), submitTextText.getText().toString(),
                        submitTextReddit.getText().toString(), Constants.SUBMIT_KIND_SELF,
                        submitTextCaptcha.getText().toString()).execute();
            }
        }
    });

    // Check the CAPTCHA
    new MyCaptchaCheckRequiredTask().execute();
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param uri The source of the file//from  w  ww.j  ava 2 s.  com
 */
public static void playFile(final Uri uri) {
    // TODO: Check for PHONE_STATE Permissions here.

    if (uri == null || mService == null) {
        return;
    }

    // If this is a file:// URI, just use the path directly instead
    // of going through the open-from-file descriptor code path.
    String filename;
    String scheme = uri.getScheme();
    if ("file".equals(scheme)) {
        filename = uri.getPath();
    } else {
        filename = uri.toString();
    }

    try {
        mService.stop();
        mService.openFile(filename);
        mService.play();
    } catch (final RemoteException ignored) {
    }
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private CensorPayload checkURL(String checkURL) throws IllegalArgumentException, URISyntaxException {
    if (!checkURL.startsWith("http"))
        checkURL = "http://" + checkURL;

    CensorPayload censorPayload = new CensorPayload(checkURL);

    Uri mUri = Uri.parse(checkURL);

    if (null == mUri.getEncodedQuery()) {
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath();
    } else {// w  w  w.  j a va 2  s  . co m
        checkURL = mUri.getScheme() + "://" + mUri.getHost() + mUri.getPath() + "?"
                + URLEncoder.encode(mUri.getEncodedQuery());
    }

    Log.e("Checking url", checkURL);

    client = new DefaultHttpClient();

    /*headRequest = new HttpHead(checkURL);
    headRequest.setHeader("User-Agent", "OONI Android Probe");*/

    httpGet = new HttpGet(checkURL);
    httpGet.setHeader("User-Agent", "OONI Android Probe");

    try {
        //response = client.execute(headRequest);
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(HttpResponse httpResponse, HttpContext httpContext)
                    throws HttpException, IOException {
                if (httpResponse.getStatusLine().getStatusCode() == 302
                        || httpResponse.getStatusLine().getStatusCode() == 301) {
                    for (Header hdr : httpResponse.getAllHeaders()) {
                        if (hdr.getName().equals("Location")) {
                            /*if (hdr.getValue().equals("http://ee-outage.s3.amazonaws.com/content-blocked/content-blocked-v1.html") ||
                            hdr.getValue().contains("http://ee-outage.s3.amazonaws.com"))
                            {
                            Log.e("Blocked", "Blocked by EE");
                            throw new CensoredException("Blocked by EE", "EE", 100);
                            }
                            else if (hdr.getValue().contains("http://www.t-mobile.co.uk/service/wnw-mig/entry/") ||
                                 hdr.getValue().contains("http://tmobile.ee.co.uk/common/system_error_pages/outage_wnw.html"))
                            {
                            Log.e("Blocked", "Blocked by TMobile");
                            throw new CensoredException("Blocked by TMobile", "TMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://online.vodafone.co.uk/dispatch/Portal/ContentControlServlet?type=restricted"))
                            {
                            Log.e("Blocked", "Blocked by Vodafone");
                            throw new CensoredException("Blocked by Vodafone", "Vodafone", 100);
                            }
                            else if (hdr.getValue().contains("http://blockpage.bt.com/pcstaticpage/blocked.html"))
                            {
                            Log.e("Blocked", "Blocked by BT");
                            throw new CensoredException("Blocked by BT", "BT", 100);
                            }
                            else if (hdr.getValue().contains("http://www.talktalk.co.uk/notice/parental-controls?accessurl"))
                            {
                            Log.e("Blocked", "Blocked by TalkTalk");
                            throw new CensoredException("Blocked by TalkTalk", "TalkTalk", 100);
                            }
                            else if (hdr.getValue().contains("http://www.plus.net/support/security/abuse/blocked.shtml"))
                            {
                            Log.e("Blocked", "Blocked by PlusNet");
                            throw new CensoredException("Blocked by PlusNet", "PlusNet", 100);
                            }
                            else if (hdr.getValue().contains("http://mobile.three.co.uk/pc/Live/pcreator/live/100004/pin/blocked?"))
                            {
                            Log.e("Blocked", "Blocked by Three");
                            throw new CensoredException("Blocked by Three", "Three", 100);
                            }
                            else if (hdr.getValue().contains("http://m.virginmedia.com/MiscPages/AdultWarning.aspx"))
                            {
                            Log.e("Blocked", "Blocked by VirginMobile");
                            throw new CensoredException("Blocked by VirginMobile", "VirginMobile", 100);
                            }
                            else if (hdr.getValue().contains("http://assets.o2.co.uk/18plusaccess/"))
                            {
                            Log.e("Blocked", "Blocked by O2");
                            throw new CensoredException("Blocked by O2", "O2", 100);
                            }*/
                            api.checkHeader(hdr);
                        }
                    }
                }

                /*Log.e("intercepted return code",httpResponse.getStatusLine().toString());
                        
                for(Header hdr : httpResponse.getAllHeaders())
                {
                Log.e("intercepted header",hdr.getName().toString() + " / " + hdr.getValue().toString());
                }
                Log.e("intercepted header","------------------\r\n------------------\r\n------------------\r\n------------------\r\n------------------\r\n");*/

            }
        });
        response = client.execute(httpGet);
    }
    //This is the best case scenario!
    catch (CensoredException CE) {
        censorPayload.consumeCensoredException(CE);
        return censorPayload;
    } catch (UnknownHostException uhe) {
        uhe.printStackTrace();
        censorPayload.consumeError(uhe.getMessage());
        return censorPayload;
    } catch (ConnectTimeoutException CTE) {
        CTE.printStackTrace();
        censorPayload.consumeError(CTE.getMessage());
        return censorPayload;
    } catch (NoHttpResponseException NHRE) {
        NHRE.printStackTrace();
        censorPayload.consumeError(NHRE.getMessage());
        return censorPayload;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        censorPayload.consumeError(ioe.getMessage());
        return censorPayload;
    } catch (IllegalStateException ise) {
        ise.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    } catch (Exception e) {
        e.printStackTrace();
        censorPayload.setCensored(false);
        censorPayload.setConfidence(0);
        return censorPayload;
    }

    int statusCode = response.getStatusLine().getStatusCode();

    censorPayload.setReturnCode(statusCode);

    Log.e("checkURL code", Integer.toString(statusCode));
    if (statusCode == 403 || statusCode == 404) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(25);
        return censorPayload;
    } else if (statusCode == 504 || statusCode == 503 || statusCode == 500) {
        censorPayload.consumeError("Server Issue " + Integer.toString(statusCode));
        return censorPayload;
    }

    String phrase = response.getStatusLine().getReasonPhrase();

    Log.e("checkURL phrase", phrase);

    if (phrase.contains("orbidden")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(50);
        return censorPayload;
    }

    if (phrase.contains("blocked")) {
        censorPayload.setCensored(true);
        censorPayload.setConfidence(100);
        return censorPayload;
    }

    for (Header hdr : response.getAllHeaders()) {
        Log.e("checkURL header", hdr.getName() + " / " + hdr.getValue());
    }

    censorPayload.setCensored(false);
    censorPayload.setConfidence(1);
    return censorPayload;
}

From source file:ch.luklanis.esscan.history.HistoryActivity.java

private Intent createShareIntent(String mime, Uri dtaFileUri) {
    String[] recipients = new String[] { PreferenceManager.getDefaultSharedPreferences(this)
            .getString(PreferencesActivity.KEY_EMAIL_ADDRESS, "") };
    String subject = getResources().getString(R.string.history_share_as_dta_title);
    String text = String.format(getResources().getString(R.string.history_share_as_dta_summary),
            dtaFileUri.getPath());

    Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    intent.setType(mime);/*from w ww  .  ja v  a 2 s .com*/

    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, text);

    intent.putExtra(Intent.EXTRA_STREAM, dtaFileUri);

    return intent;
}

From source file:com.android.providers.downloads.DownloadInfo.java

/**
 * Returns whether this download should be enqueued.
 *///w w  w  . jav a 2  s .c o m
private boolean isReadyToDownload() {
    if (mControl == Downloads.Impl.CONTROL_PAUSED) {
        // the download is paused, so it's not going to start
        Log.i(Constants.DL_ENHANCE, "Download is paused " + "then no need to start");
        return false;
    }
    switch (mStatus) {
    case 0: // status hasn't been initialized yet, this is a new download
    case Downloads.Impl.STATUS_PENDING: // download is explicit marked as ready to start
    case Downloads.Impl.STATUS_RUNNING: // download interrupted (process killed etc) while
                                        // running, without a chance to update the database
        return true;

    case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
    case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
        return checkCanUseNetwork(mTotalBytes) == NetworkState.OK;

    case Downloads.Impl.STATUS_WAITING_TO_RETRY:
        // download was waiting for a delayed restart
        final long now = mSystemFacade.currentTimeMillis();
        return restartTime(now) <= now;
    case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
        // is the media mounted?
        final Uri uri = Uri.parse(mUri);
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            final File file = new File(uri.getPath());
            return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState(file));
        } else {
            Log.w(TAG, "Expected file URI on external storage: " + mUri);
            return false;
        }
        /// M: Because OMA DL spec, if insufficient memory, we
        /// will show to user but not retry.
        //case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
        // should check space to make sure it is worth retrying the download.
        // but thats the first thing done by the thread when it retries to download
        // it will fail pretty quickly if there is no space.
        // so, it is not that bad to skip checking space availability here.
        //return true;
        /// M: Add for fix alp00406729, file already exist but user do not operation. @{
    case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
        return false;
    /// @}
    }
    return false;
}

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

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }// w ww  .j  a  v a  2 s.co m

    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new OpenUriException(false, new IOException("Uri had no scheme"));
    }

    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);
        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:com.polyvi.xface.extension.zip.XZipExt.java

/**
 * ??zip?/*w  ww . ja  v a2s  . c  o  m*/
 *
 * @param dstFileUri
 *            
 * @param is
 *            ?zip?
 * @return ??
 * @throws IOException
 * @throws FileNotFoundException
 * @throws IllegalArgumentException
 */
private void unzipFileFromStream(Uri dstFileUri, InputStream is)
        throws IOException, FileNotFoundException, IllegalArgumentException {
    if (null == dstFileUri || null == is) {
        XLog.e(CLASS_NAME, "Method unzipFileFromStream: params is null");
        throw new IllegalArgumentException();
    }
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry = null;
    Uri unZipUri = null;
    while (null != (entry = zis.getNextEntry())) {
        File unZipFile = new File(dstFileUri.getPath() + File.separator + entry.getName());
        unZipUri = Uri.fromFile(unZipFile);
        if (entry.isDirectory()) {
            if (!unZipFile.exists()) {
                unZipFile.mkdirs();
            }
        } else {
            // ???
            prepareForZipDir(unZipUri);
            OutputStream fos = mResourceApi.openOutputStream(unZipUri);
            int readLen = 0;
            byte buffer[] = new byte[XConstant.BUFFER_LEN];
            while (-1 != (readLen = zis.read(buffer))) {
                fos.write(buffer, 0, readLen);
            }
            fos.close();
        }
    }
    zis.close();
    is.close();
}

From source file:com.cn.pppcar.UserBaseInformationAct.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == Constants.REQUEST_OPEN_GALARY_FOR_HEAD_PORTRAIT) {
            final Uri selectedUri = data.getData();
            if (selectedUri != null) {
                imageHandler.startCropActivity(data.getData(), UserBaseInformationAct.this);
            } else {
                Toast.makeText(this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
            }//w ww  .ja v a  2 s . c o  m
        } else if (requestCode == UCrop.REQUEST_CROP) {
            handleCropResult(data);
        } else if (requestCode == Constants.REQUEST_OPEN_CAMERA_FOR_HEAD_PORTRAIT) {
            Uri uri = imageHandler.getCapturedImageUri();
            imageHandler.startCropActivity(uri, UserBaseInformationAct.this);
        } else if (requestCode == Constants.REQUEST_OPEN_GALARY_FOR_BUSINESS_LICENSE) {
            final Uri selectedUri = data.getData();
            if (selectedUri != null) {
                licenseImg.setImageURI(selectedUri);
            } else {
                Toast.makeText(this, "?Uri", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == Constants.REQUEST_OPEN_CAMERA_FOR_BUSINESS_LICENSE) {
            Uri uri = imageHandler.getCapturedImageUri();
            Bitmap bmp = imageHandler.decodeSampledBitmapFromFile(uri.getPath(), 600, 800);
            uri = imageHandler.compress(UserBaseInformationAct.this, bmp);
            licenseImg.setImageURI(uri);

        }
    }
    if (resultCode == UCrop.RESULT_ERROR) {
        imageHandler.handleCropError(data, UserBaseInformationAct.this);
    }
}

From source file:com.musenkishi.wally.activities.ImageDetailsActivity.java

private void handleSavedImageData(Uri filePath) {
    if (filePath != null && filePath.getPath() != null) {
        Message msgObj = uiHandler.obtainMessage();
        msgObj.what = currentHandlerCode;
        msgObj.obj = filePath;// w  w w  . ja  v  a  2  s. c om
        uiHandler.sendMessage(msgObj);
        MediaScannerConnection.scanFile(getApplicationContext(), new String[] { filePath.getPath() }, null,
                new MediaScannerConnection.MediaScannerConnectionClient() {
                    @Override
                    public void onMediaScannerConnected() {

                    }

                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        getApplication().sendBroadcast(new Intent(FileChangeReceiver.FILES_CHANGED));
                    }
                });
    }
}

From source file:com.owncloud.android.ui.helpers.UriUploader.java

public UriUploaderResultCode uploadUris() {

    try {/*from  www . j a  v  a 2  s. c  om*/

        List<Uri> contentUris = new ArrayList<>();
        List<String> contentRemotePaths = new ArrayList<>();

        int schemeFileCounter = 0;

        for (Parcelable sourceStream : mUrisToUpload) {
            Uri sourceUri = (Uri) sourceStream;
            if (sourceUri != null) {
                String displayName = UriUtils.getDisplayNameForUri(sourceUri, mActivity);
                if (displayName == null) {
                    displayName = generateDiplayName();
                }
                String remotePath = mUploadPath + displayName;

                if (ContentResolver.SCHEME_CONTENT.equals(sourceUri.getScheme())) {
                    contentUris.add(sourceUri);
                    contentRemotePaths.add(remotePath);

                } else if (ContentResolver.SCHEME_FILE.equals(sourceUri.getScheme())) {
                    /// file: uris should point to a local file, should be safe let FileUploader handle them
                    requestUpload(sourceUri.getPath(), remotePath);
                    schemeFileCounter++;
                }
            }
        }

        if (!contentUris.isEmpty()) {
            /// content: uris will be copied to temporary files before calling {@link FileUploader}
            copyThenUpload(contentUris.toArray(new Uri[contentUris.size()]),
                    contentRemotePaths.toArray(new String[contentRemotePaths.size()]));

        } else if (schemeFileCounter == 0) {
            mCode = UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD;

        }

    } catch (SecurityException e) {
        mCode = UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED;
        Log_OC.e(TAG, "Permissions fail", e);

    } catch (Exception e) {
        mCode = UriUploaderResultCode.ERROR_UNKNOWN;
        Log_OC.e(TAG, "Unexpected error", e);

    }
    return mCode;
}