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:com.android.app.MediaPlaybackActivity.java

private void startPlayback() {

    if (mService == null)
        return;/*from w  w w.j  a  v a2 s .  c  om*/
    Intent intent = getIntent();
    String filename = "";
    Uri uri = intent.getData();
    if (uri != null && uri.toString().length() > 0) {
        // If this is a file:// URI, just use the path directly instead
        // of going through the open-from-filedescriptor codepath.
        String scheme = uri.getScheme();
        if ("file".equals(scheme)) {
            filename = uri.getPath();
        } else {
            filename = uri.toString();
        }

        try {
            mService.stop();
            mService.openFile(filename);
            mService.play();
            setIntent(new Intent());
        } catch (Exception ex) {
            Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
        }
    }

    updateTrackInfo();
    long next = refreshNow();
    queueNextRefresh(next);
}

From source file:com.ccxt.whl.activity.SettingsFragmentCopy.java

/**
 * ?uri?/*from w  w  w .  java  2 s.c o  m*/
 * 
 * @param selectedImage
 */
private void sendPicByUri(Uri selectedImage) {
    // String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().getContentResolver().query(selectedImage, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex("_data");
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        cursor = null;

        if (picturePath == null || picturePath.equals("null")) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        copyFile(picturePath, imageUri.getPath());
        cropImageUri(imageUri, 150, 150, USERPIC_REQUEST_CODE_CUT);
        //sendPicture(picturePath);
    } else {
        File file = new File(selectedImage.getPath());
        if (!file.exists()) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;

        }
        copyFile(selectedImage.getPath(), imageUri.getPath());
        cropImageUri(imageUri, 150, 150, USERPIC_REQUEST_CODE_CUT);
        //sendPicture(file.getAbsolutePath());
    }
    /*if(getpathfromUri(uri)!=null&&getpathfromUri(imageUri)!=null){
        copyFile(getpathfromUri(uri),getpathfromUri(imageUri));
       }else{
    return;
       }*/
    //cropImageUri(selectedImage, 150, 150, USERPIC_REQUEST_CODE_CUT);

}

From source file:com.cerema.cloud2.ui.activity.FileDisplayActivity.java

private void requestSimpleUpload(Intent data, int resultCode) {
    String filePath = null;//  ww w.j a  va  2s  .co  m
    String mimeType = null;

    Uri selectedImageUri = data.getData();

    try {
        mimeType = getContentResolver().getType(selectedImageUri);

        String fileManagerString = selectedImageUri.getPath();
        String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);

        if (selectedImagePath != null)
            filePath = selectedImagePath;
        else
            filePath = fileManagerString;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception when trying to read the result of " + "Intent.ACTION_GET_CONTENT",
                e);

    } finally {
        if (filePath == null) {
            Log_OC.e(TAG, "Couldn't resolve path to file");
            Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content),
                    Toast.LENGTH_LONG);
            t.show();
            return;
        }
    }

    Intent i = new Intent(this, FileUploader.class);
    i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
    OCFile currentDir = getCurrentDir();
    String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;

    if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
        Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                Log_OC.v(TAG, "Display Name: " + displayName);

                displayName.replace(File.separatorChar, '_');
                displayName.replace(File.pathSeparatorChar, '_');
                remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);

            }
            // and what happens in case of error?; wrong target name for the upload
        } finally {
            cursor.close();
        }

    } else {
        remotePath += new File(filePath).getName();
    }

    i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
    i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
    i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
    i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
    if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
        i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
    startService(i);
}

From source file:com.indoorsy.frash.easemob.activity.ChatActivity.java

/**
 * ?uri??//from  w w  w  .j  a  v  a 2  s  .  c  o  m
 * 
 * @param selectedImage
 */
private void sendPicByUri(Uri selectedImage) {
    // String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex("_data");
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        cursor = null;
        if (picturePath == null || picturePath.equals("null")) {
            Toast toast = Toast.makeText(this, R.string.not_find_image, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        sendPicture(picturePath);
    } else {
        File file = new File(selectedImage.getPath());
        if (!file.exists()) {
            Toast toast = Toast.makeText(this, R.string.not_find_image, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        sendPicture(file.getAbsolutePath());
    }
}

From source file:com.material.katha.wifidirectmp3.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.

    if (requestCode >= 0 && resultCode == -1 && data != null) {

        // count++;
        Uri uri = data.getData();
        String abc = uri.toString();
        // System.out.println(abc);
        Log.d("katha", abc + "abc");
        try {/*from  w  ww .j  a  v  a 2s . c om*/
            datapath = getPath(getActivity(), uri);
            Log.d("WiFiDirectActivity", datapath.substring(datapath.lastIndexOf("/") + 1, datapath.length()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        String filename = abc.substring(abc.lastIndexOf("/") + 1);
        pd = new ProgressDialog(getActivity());
        pd.setMessage("Sending:" + datapath);
        pd.setButton(DialogInterface.BUTTON_NEGATIVE, "Pause", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                Log.d("WiFiDirectActivity", "pause pressed");
                resetafterdismiss(0);
                pause++;
                //pd.show();
            }
        });
        pd.show();

        File f = new File(uri.getPath());
        //long file_size = f.length();
        ContentResolver cr = getActivity().getContentResolver();
        InputStream is = null;
        int fsize = 0;
        try {
            //is=cr.openInputStream(Uri.parse(new File("DCIM/Camera/IMG_20160118_090231.jpg").toString()));
            is = cr.openInputStream(uri);
            fsize = is.available();

            Log.d("WiFiDirectActivity", "File size is:" + is.available() + "               " + f.getName()
                    + "uri  " + uri + "f  " + f + "file name " + f.getName());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d("WifiDirectActivity", "here " + e);
        } catch (IOException e) {
            Log.d("WifiDirectActivity", "here " + e);
            e.printStackTrace();
        }

        //Log.d("katha", fileext + "fileext");
        //;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;change fileext = abc.substring(abc.lastIndexOf('.'));

        /*progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Sending file:"+abc);
        progressDialog.show();
        */

        // progressDialog = ProgressDialog.show(getActivity(), "Sending","Copying file :" + fileext, true, true);
        // makeText(getActivity(), fileext, LENGTH_LONG).show();
        TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
        //  statusText.setText("Sending: " + uri);
        // String devicename = "abc";
        //            devicename = device.deviceName;
        // Toast.makeText(getActivity(),devicename,Toast.LENGTH_LONG).show();

        Log.d("WiFiDirectActivity", "Intent----------- " + uri);
        Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
        serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
        Log.d("WiFiDirectActivity", "Action" + FileTransferService.ACTION_SEND_FILE + "\n\n\n\n");
        ////////////////////serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
        serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, datapath);

        serviceIntent.putExtra(FileTransferService.FILE_SIZE, fsize);

        //serviceIntent.putExtra(FileTransferService.device_name,devicename);
        serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
        String localip = getDottedDecimalIP(getLocalIPAddress());
        Localip = localip;
        Log.d("WiFiDirectActivity", "DEVICE_NAME: " + devicename);
        serviceIntent.putExtra(FileTransferService.DEVICE_NAME, devicename);

        if (localip.equals("192.168.49.1")) {
            Log.d("WiFiDirectActivity", "Flag is 0.");
            //  devicename = device.deviceName;
            serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, client_ip);
            serviceIntent.putExtra(FileTransferService.Client_add, client_ip);
            ;
        } else {
            Log.d("WiFiDirectActivity", "Flag is 1.");
            //devicename = device.deviceName;
            // Toast.makeText(getActivity(),devicename,Toast.LENGTH_LONG).show();
            try {
                serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
                        info.groupOwnerAddress.getHostAddress());
                serviceIntent.putExtra(FileTransferService.Client_add, localip);
            } catch (Exception e) {
                Toast.makeText(getActivity(), "Error!!", LENGTH_LONG).show();
                Log.d("WiFiDirectActivity", "error in catch!!");
                return;
            }
        }
        getActivity().startService(serviceIntent);
        Log.d("WiFiDirectActivity", "here");
    } else {
        return;
    }

}

From source file:com.ccxt.whl.activity.SettingsFragmentC_0815.java

/**
 * ?uri?/*from  ww w  .  jav  a 2 s.com*/
 * 
 * @param selectedImage
 */
private void sendPicByUri(Uri selectedImage) {
    // String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().getContentResolver().query(selectedImage, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex("_data");
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        cursor = null;

        if (picturePath == null || picturePath.equals("null")) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;
        }
        //copyFile(picturePath,imageUri.getPath());
        cropImageUri(selectedImage, 200, 200, USERPIC_REQUEST_CODE_CUT);
        //sendPicture(picturePath);
    } else {
        File file = new File(selectedImage.getPath());
        if (!file.exists()) {
            Toast toast = Toast.makeText(getActivity(), "?", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            return;

        }
        //copyFile(selectedImage.getPath(),imageUri.getPath());
        cropImageUri(selectedImage, 200, 200, USERPIC_REQUEST_CODE_CUT);
        //sendPicture(file.getAbsolutePath());
    }
    /*if(getpathfromUri(uri)!=null&&getpathfromUri(imageUri)!=null){
        copyFile(getpathfromUri(uri),getpathfromUri(imageUri));
       }else{
    return;
       }*/
    //cropImageUri(selectedImage, 150, 150, USERPIC_REQUEST_CODE_CUT);

}

From source file:com.appunite.socketio.SocketIOBase.java

private ConnectionResult connect(String url)
        throws WrongHttpResponseCode, IOException, WrongSocketIOResponse, InterruptedException {
    Uri uri = Uri.parse(url);

    synchronized (mInterruptionLock) {
        if (mInterrupted) {
            throw new InterruptedException();
        }/*from   ww  w  .  j ava  2s .  c o  m*/
        mRequest = new HttpGet(url);
    }
    HTTPUtils.setupDefaultHeaders(mRequest);

    HttpResponse response = getClient().execute(mRequest);
    synchronized (mInterruptionLock) {
        if (mRequest.isAborted() || mInterrupted) {
            mRequest = null;
            throw new InterruptedException();
        }
        mRequest = null;
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new WrongHttpResponseCode(response);
    }

    String responseStr = HTTPUtils.getStringFromResponse(response);
    StringTokenizer responseSplit = new StringTokenizer(responseStr, ":");

    ConnectionResult result = new ConnectionResult();
    try {
        result.sessionId = responseSplit.nextToken();
        if (TextUtils.isEmpty(result.sessionId)) {
            throw new WrongSocketIOResponse("Empty socket io session id");
        }

        result.timeout = getIntOrAbsetFromString(responseSplit.nextToken());
        result.heartbeat = getIntOrAbsetFromString(responseSplit.nextToken());

        ImmutableSet<String> types = getTypesFromString(responseSplit.nextToken());
        if (!types.contains("websocket")) {
            throw new WrongSocketIOResponse("Websocket not found in server response");
        }
    } catch (NoSuchElementException e) {
        throw new WrongSocketIOResponse("Not enough color separated values in response", e);
    }
    result.socketUri = new Uri.Builder().scheme("ws").encodedAuthority(uri.getEncodedAuthority())
            .path(uri.getPath()).appendPath("websocket").appendPath(result.sessionId).build();
    return result;
}

From source file:cgeo.geocaching.connector.gc.GCParser.java

/**
 * Upload an image to a log that has already been posted
 *
 * @param logId/*  ww w .  j  a  v a2s . c  om*/
 *            the ID of the log to upload the image to. Found on page returned when log is uploaded
 * @param caption
 *            of the image; max 50 chars
 * @param description
 *            of the image; max 250 chars
 * @param imageUri
 *            the URI for the image to be uploaded
 * @return status code to indicate success or failure
 */
public static ImmutablePair<StatusCode, String> uploadLogImage(final String logId, final String caption,
        final String description, final Uri imageUri) {
    final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com")
            .path("/seek/upload.aspx").encodedQuery("LID=" + logId).build().toString();

    final String page = GCLogin.getInstance().getRequestLogged(uri, null);
    if (StringUtils.isBlank(page)) {
        Log.e("GCParser.uploadLogImage: No data from server");
        return new ImmutablePair<StatusCode, String>(StatusCode.UNKNOWN_ERROR, null);
    }
    assert page != null;

    final String[] viewstates = GCLogin.getViewstates(page);

    final Parameters uploadParams = new Parameters("__EVENTTARGET", "", "__EVENTARGUMENT", "",
            "ctl00$ContentBody$ImageUploadControl1$uxFileCaption", caption,
            "ctl00$ContentBody$ImageUploadControl1$uxFileDesc", description,
            "ctl00$ContentBody$ImageUploadControl1$uxUpload", "Upload");
    GCLogin.putViewstates(uploadParams, viewstates);

    final File image = new File(imageUri.getPath());
    final String response = Network.getResponseData(Network.postRequest(uri, uploadParams,
            "ctl00$ContentBody$ImageUploadControl1$uxFileUpload", "image/jpeg", image));

    final MatcherWrapper matcherUrl = new MatcherWrapper(GCConstants.PATTERN_IMAGE_UPLOAD_URL, response);

    if (matcherUrl.find()) {
        Log.i("Logimage successfully uploaded.");
        final String uploadedImageUrl = matcherUrl.group(1);
        return ImmutablePair.of(StatusCode.NO_ERROR, uploadedImageUrl);
    }
    Log.e("GCParser.uploadLogIMage: Failed to upload image because of unknown error");

    return ImmutablePair.of(StatusCode.LOGIMAGE_POST_ERROR, null);
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

private int queryOrientation(Uri uri) {
    Log.d(Application.TAG, "querying " + uri.toString());

    ContentResolver cr = ActivityUploader.this.getContentResolver();

    int orientation = 0;

    Cursor c = cr.query(uri, new String[] { MediaStore.Images.ImageColumns.ORIENTATION, }, null, null, null);

    if (c != null) {
        c.moveToFirst();/*  ww  w .j  a  va 2 s .c  o m*/
        orientation = c.getInt(0);
        c.close();

        return orientation;
    }

    /* If there's no such item in ContentResolver, query EXIF */
    return queryExifOrientation(uri.getPath());
}

From source file:Main.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>//from w w w .j  a va  2s  .c  om
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri     The Uri to query.
 * @author paulburke
 * @see #isLocal(String)
 * @see #getFile(Context, Uri)
 */
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}