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:edu.mit.mobile.android.locast.sync.MediaSync.java

/**
 * Synchronize the media of the given castMedia. It will download or upload as needed.
 *
 * Blocks until the sync is complete.//  ww w .  j a  va 2  s .  c om
 *
 * @param castMediaUri
 *            a {@link CastMedia} item uri
 * @throws SyncException
 */
public void syncItemMedia(Uri castMediaUri) throws SyncException {

    final Cursor castMedia = mCr.query(castMediaUri, CASTMEDIA_PROJECTION, null, null, null);

    final Uri castUri = CastMedia.getCast(castMediaUri);
    final Cursor cast = mCr.query(castUri, CAST_PROJECTION, null, null, null);

    try {
        if (!castMedia.moveToFirst()) {
            throw new IllegalArgumentException("uri " + castMediaUri + " has no content");
        }

        if (!cast.moveToFirst()) {
            throw new IllegalArgumentException(castMediaUri + " cast " + castUri + " has no content");
        }

        // cache the column numbers
        final int mediaUrlCol = castMedia.getColumnIndex(CastMedia._MEDIA_URL);
        final int localUriCol = castMedia.getColumnIndex(CastMedia._LOCAL_URI);

        final boolean isFavorite = cast.getInt(cast.getColumnIndex(Cast._FAVORITED)) != 0;
        final boolean keepOffline = castMedia.getInt(castMedia.getColumnIndex(CastMedia._KEEP_OFFLINE)) != 0;

        final String mimeType = castMedia.getString(castMedia.getColumnIndex(CastMedia._MIME_TYPE));

        final boolean isImage = (mimeType != null) && mimeType.startsWith("image/");

        // we don't need to sync this
        if ("text/html".equals(mimeType)) {
            return;
        }

        final Uri locMedia = castMedia.isNull(localUriCol) ? null : Uri.parse(castMedia.getString(localUriCol));
        final String pubMedia = castMedia.getString(mediaUrlCol);
        final boolean hasLocMedia = locMedia != null && new File(locMedia.getPath()).exists();
        final boolean hasPubMedia = pubMedia != null && pubMedia.length() > 0;

        final String localThumb = castMedia.getString(castMedia.getColumnIndex(CastMedia._THUMB_LOCAL));

        if (hasLocMedia && !hasPubMedia) {
            final String uploadPath = castMedia.getString(castMedia.getColumnIndex(CastMedia._PUBLIC_URI));
            if (uploadPath == null) {
                Log.w(TAG, "attempted to sync " + castMediaUri + " which has a null uploadPath");
                return;
            }
            uploadMedia(uploadPath, castMediaUri, mimeType, locMedia);

        } else if (!hasLocMedia && hasPubMedia) {
            // only have a public copy, so download it and store locally.
            final Uri pubMediaUri = Uri.parse(pubMedia);
            final File destfile = getFilePath(pubMediaUri);

            // the following conditions indicate that the cast media should be downloaded.
            if (keepOffline || isFavorite) {
                final boolean anythingChanged = downloadMediaFile(pubMedia, destfile, castMediaUri);

                // the below is inverted from what seems logical, because downloadMediaFile()
                // will actually update the castmedia if it downloads anything. We'll only be
                // getting here if we don't have any local record of the file, so we should make
                // the association by ourselves.
                if (!anythingChanged) {
                    File thumb = null;
                    if (isImage && localThumb == null) {
                        thumb = destfile;
                    }
                    updateLocalFile(castMediaUri, destfile, thumb);
                    // disabled to avoid spamming the user with downloaded
                    // items.
                    // checkForMediaEntry(castMediaUri, pubMediaUri, mimeType);
                }
            }
        }
    } finally {
        cast.close();
        castMedia.close();
    }
}

From source file:com.nanostuffs.yurdriver.fragment.RegisterFragment.java

private String getRealPathFromURI(Uri contentURI) {
    String result;//from w  w  w  . j a  va 2 s.c om
    Cursor cursor = registerActivity.getContentResolver().query(contentURI, null, null, null, null);

    if (cursor == null) { // Source is Dropbox or other similar local file
        // path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

From source file:com.rks.musicx.misc.utils.Helper.java

/**
 * return real path of image/*from ww w .j av  a2  s .c  om*/
 *
 * @param uri
 * @param context
 * @return
 */
public static String getRealPathFromURI(Uri uri, Context context) {
    if (uri == null) {
        return null;
    }
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        cursor.close();
        return path;
    }
    return uri.getPath();
}

From source file:com.google.plus.wigwamnow.social.FacebookProvider.java

/**
 * Post a photo from a {@link Uri} to the user's WigwamNow album.
 *//*from   w ww . ja v a 2  s .c  o m*/
@Override
public boolean postPhoto(Uri photoUri, Activity activity) {
    final WigwamDetailActivity wda = (WigwamDetailActivity) activity;

    Session session = Session.getActiveSession();
    if (!hasPublishPermissions()) {
        requestPublishPermissions(session, activity);
        return false;
    }

    String postingPhotoString = activity.getResources().getString(R.string.posting_photo);
    showProgressDialog(postingPhotoString, activity);

    Request.Callback callback = new Request.Callback() {
        @Override
        public void onCompleted(Response response) {
            onPostActionResponse(response, wda);
        }
    };

    Bitmap bitmap = BitmapFactory.decodeFile(photoUri.getPath());
    Request request = Request.newUploadPhotoRequest(session, bitmap, callback);
    request.executeAsync();

    return true;
}

From source file:com.wikitude.virtualhome.AugmentedActivity.java

public String getPath(Uri uri) {
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();//from  w w  w .  j a v  a 2 s.  c  om
        return cursor.getString(column_index);
    }
    // this is our fallback here
    return uri.getPath();
}

From source file:Main.java

/** 
 * Get a GhostMySelfie 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.
 * //from   w w  w .  j  ava 2 s . c om
 * @param context The context. 
 * @param uri The Uri to query. 
 * 
 * return selfieFilePath
 */
public static String getPath(final Context context, final Uri uri) {
    // Check if the version of current device is greater 
    // than API 19 (KitKat).
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider.
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider 
        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];
            }
        }
        // DownloadsProvider 
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse(DOWNLOADS_PROVIDER_PATH),
                    Long.valueOf(id));

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

            final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

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

            // Get the FilePath from GhostMySelfie MediStore
            // for given Uri, selection, selectionArgs.
            return getGhostMySelfieDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general) .
    else if ("content".equalsIgnoreCase(uri.getScheme()))
        return getGhostMySelfieDataColumn(context, uri, null, null);
    // File 
    else if ("file".equalsIgnoreCase(uri.getScheme()))
        return uri.getPath();

    return null;
}

From source file:com.mobicage.rogerthat.plugins.messaging.widgets.PhotoUploadWidget.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Crop.REQUEST_CROP) {
        handleCrop(resultCode, data);/* w w w . j av  a 2 s.c  om*/
    } else if (requestCode == PICK_IMAGE) {
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && data.getData() != null) {
                if (mRatio == null) {
                    final Uri selectedImage = data.getData();

                    final ProgressDialog progressDialog = new ProgressDialog(mActivity);
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progressDialog.setMessage(mActivity.getString(R.string.processing));
                    progressDialog.setCancelable(false);
                    progressDialog.show();

                    new SafeAsyncTask<Object, Object, Boolean>() {
                        @Override
                        protected Boolean safeDoInBackground(Object... params) {
                            L.d("Processing picture: " + selectedImage.getPath());
                            try {
                                File tmpUploadFile = getTmpUploadPhotoLocation();
                                if (tmpUploadFile.getAbsolutePath().equals(selectedImage.getPath())) {
                                    return true;
                                } else {
                                    InputStream is = mActivity.getContentResolver()
                                            .openInputStream(selectedImage);
                                    if (is != null) {
                                        try {
                                            OutputStream out = new FileOutputStream(tmpUploadFile);
                                            try {
                                                IOUtils.copy(is, out, 1024);
                                            } finally {
                                                out.close();
                                            }
                                        } finally {
                                            is.close();
                                        }
                                        return true;
                                    }
                                }
                            } catch (FileNotFoundException e) {
                                L.d(e);
                            } catch (Exception e) {
                                L.bug("Unknown exception occured while processing picture: "
                                        + selectedImage.toString(), e);
                            }

                            return false;
                        };

                        @Override
                        protected void safeOnPostExecute(Boolean result) {
                            progressDialog.dismiss();
                            if (result) {
                                handleSelection();
                            } else {
                                UIUtils.showLongToast(getContext(), R.string.crop__pick_error);
                            }
                        }

                        @Override
                        protected void safeOnCancelled(Boolean result) {
                        }

                        @Override
                        protected void safeOnProgressUpdate(Object... values) {
                        }

                        @Override
                        protected void safeOnPreExecute() {
                        };
                    }.execute();

                } else {
                    beginCrop(data.getData());
                    return;
                }
            } else {
                if (mRatio == null) {
                    handleSelection();
                } else {
                    beginCrop(mUriSavedImage);
                }
            }
        }
    } else {
        L.bug("Unexpected request code in onActivityResult: " + requestCode);
    }
}

From source file:edu.mit.mobile.android.locast.data.Sync.java

/**
 * Sync the given URI to the server. Will compare dates and do a two-way sync.
 * Does not yet handle the case where both server and and local are modified
 * (collisions)/*from   w  ww . ja va 2  s .com*/
 *
 * @param toSync URI of the object to sync. Generally, this should be the dir URI
 * @param sync A new object that extends JsonSyncableItem. This is needed for the JSON
 * serialization routine in it, as well as the sync map.
 * @throws IOException
 */
private void sync(Uri toSync, JsonSyncableItem sync, SyncProgressNotifier syncProgress, Bundle extras)
        throws SyncException, IOException {
    String netPath;
    boolean haveItemPubUri = false;

    if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
        netPath = toSync.getPath();
        toSync = (Uri) extras.get(EXTRA_DESTINATION_URI);
        haveItemPubUri = true;
    } else {
        netPath = null;
    }
    final String contentType = getContentResolver().getType(toSync);

    final Cursor c = cr.query(toSync, sync.getFullProjection(), null, null, null);
    try {
        syncProgress.addPendingTasks(c.getCount());

        // Handle a list of items.
        if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) {
            // load from the network first...
            if (netPath == null) {
                netPath = MediaProvider.getPublicPath(this, toSync);
            }
            syncNetworkList(toSync, netPath, sync, syncProgress);
        } else if (haveItemPubUri) {
            syncNetworkItem(toSync, netPath, sync, syncProgress);
        }

        // then load locally.

        if (DEBUG) {
            Log.d(TAG, "have " + c.getCount() + " local items to sync");
        }
        for (c.moveToFirst(); (currentSyncTask != null && !currentSyncTask.isCancelled()) && !c.isAfterLast(); c
                .moveToNext()) {
            try {
                syncItem(toSync, c, null, sync, syncProgress, netPath);
                syncProgress.completeTask();

            } catch (final SyncItemDeletedException side) {
                if (DEBUG) {
                    Log.d(TAG, side.getLocalizedMessage() + " Deleting...");
                }
                cr.delete(side.getItem(), null, null);
                //side.printStackTrace();
                syncProgress.completeTask();
                continue;
            }
        }
    } catch (final NoPublicPath npp) {
        // XXX this should be a hard error
        Log.e(TAG, "Sync Error: " + npp.getLocalizedMessage());
        return;
    } finally {
        c.close();
    }
}

From source file:com.poinsart.votar.VotarMain.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Bitmap photo = null;/*  ww w  .j a v  a  2  s .  c  om*/
    opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Uri uri = null;

    if (resultCode != RESULT_OK)
        return;

    if (requestCode == GALLERY_REQUEST && data != null && data.getData() != null) {
        uri = data.getData();
        if (uri == null)
            return;
        //User had pick an image.
        Cursor cursor = getContentResolver().query(uri,
                new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
        cursor.moveToFirst();
        //Link to the image
        lastPhotoFilePath = cursor.getString(0);
        cursor.close();
    }
    if (requestCode == CAMERA_REQUEST) {
        uri = cameraFileUri;
        lastPhotoFilePath = uri.getPath();
    }

    if (lastPhotoFilePath == null)
        return;

    lastPointsJsonString = null;

    new AnalyzeTask().execute(photo);
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
    //@Override//from   ww w. j av a2 s .c  o  m
    //public void onCreate(Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    shouldAutoPlay = true;
    clearResumePosition();
    mediaDataSourceFactory = buildDataSourceFactory(true);
    mainHandler = new Handler();
    if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
        CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
    }

    //setContentView(R.layout.player_activity);
    View rootView = v.findViewById(R.id.root);
    rootView.setOnClickListener(this);
    debugRootView = (LinearLayout) v.findViewById(R.id.controls_root);
    debugTextView = (TextView) v.findViewById(R.id.debug_text_view);
    retryButton = (Button) v.findViewById(R.id.retry_button);
    retryButton.setOnClickListener(this);
    centerInfo = (TextView) v.findViewById(R.id.centerInfo);
    //        localTime = (TextView) v.findViewById(R.id.localTime);
    //        battery = (BatteryLevelView) v.findViewById(R.id.battery);

    simpleExoPlayerView = (SimpleExoPlayerView) v.findViewById(R.id.player_view);
    simpleExoPlayerView.setControllerVisibilityListener(this);
    simpleExoPlayerView.requestFocus();

    final Intent intent = getActivity().getIntent();
    if (intent != null) {
        Uri extras = intent.getData();
        if (extras != null) {
            CURRENT_PATH = extras.getPath();
            Log.d(TAG, "intent.getData() " + CURRENT_PATH);
        }
    }
    updateColor(rootView);
}