Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

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

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

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

private String generateThumbnail(Uri castMedia, String mimeType, String locMedia) throws ThumbnailException {
    final long locId = ContentUris.parseId(Uri.parse(locMedia));

    Bitmap thumb;/*  w w w. j a  v  a  2s. c  om*/
    if (mimeType.startsWith("image/")) {
        thumb = Images.Thumbnails.getThumbnail(getContentResolver(), locId, Images.Thumbnails.MINI_KIND, null);

    } else if (mimeType.startsWith("video/")) {
        thumb = Video.Thumbnails.getThumbnail(getContentResolver(), locId, Video.Thumbnails.MINI_KIND, null);

    } else {
        throw new IllegalArgumentException(
                "cannot generate thumbnail for item with MIME type: '" + mimeType + "'");
    }

    if (thumb == null) {
        throw new ThumbnailException("Android thumbnail generator returned null");
    }

    try {
        final File outFile = new File(getCacheDir(), "thumb" + sha1Sum(locMedia) + ".jpg");
        // final File outFile = File.createTempFile("thumb", ".jpg",
        // getCacheDir());
        if (!outFile.exists()) {
            if (!outFile.createNewFile()) {
                throw new IOException("cannot create new file");
            }
            if (DEBUG) {
                Log.d(TAG, "attempting to save thumb in " + outFile);
            }
            final FileOutputStream fos = new FileOutputStream(outFile);
            thumb.compress(CompressFormat.JPEG, 75, fos);
            thumb.recycle();
            fos.close();

            if (DEBUG) {
                Log.d(TAG, "generated thumbnail for " + locMedia + " and saved it in "
                        + outFile.getAbsolutePath());
            }
        }

        return Uri.fromFile(outFile).toString();
    } catch (final IOException ioe) {
        final ThumbnailException te = new ThumbnailException();
        te.initCause(ioe);
        throw te;
    }
}

From source file:com.facebook.RequestTests.java

@LargeTest
public void testUploadVideoFileToUserId() throws IOException, URISyntaxException {
    File tempFile = null;/*from  ww  w. j a v a2 s .  c o  m*/
    try {
        GraphRequest meRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), null);
        GraphResponse meResponse = meRequest.executeAndWait();
        JSONObject meJson = meResponse.getJSONObject();
        assertNotNull(meJson);

        String userId = meJson.optString("id");
        assertNotNull(userId);

        tempFile = createTempFileFromAsset("DarkScreen.mov");
        ShareVideo video = new ShareVideo.Builder().setLocalUrl(Uri.fromFile(tempFile)).build();
        ShareVideoContent content = new ShareVideoContent.Builder().setVideo(video).build();
        final ShareApi shareApi = new ShareApi(content);
        shareApi.setGraphNode(userId);
        final AtomicReference<String> videoId = new AtomicReference<>(null);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shareApi.share(new FacebookCallback<Sharer.Result>() {
                    @Override
                    public void onSuccess(Sharer.Result result) {
                        videoId.set(result.getPostId());
                        notifyShareFinished();
                    }

                    @Override
                    public void onCancel() {
                        notifyShareFinished();
                    }

                    @Override
                    public void onError(FacebookException error) {
                        notifyShareFinished();
                    }

                    private void notifyShareFinished() {
                        synchronized (shareApi) {
                            shareApi.notifyAll();
                        }
                    }
                });
            }
        });

        synchronized (shareApi) {
            shareApi.wait(REQUEST_TIMEOUT_MILLIS);
        }
        assertNotNull(videoId.get());
    } catch (Exception ex) {
        fail();
    } finally {
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void share() {
    GalleryItemViewTag tag = getCurrentTag();
    if (tag == null)
        return;/*from   w  w  w.jav a 2s  . c om*/
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    String extension = Attachments.getAttachmentExtention(tag.attachmentModel);
    switch (tag.attachmentModel.type) {
    case AttachmentModel.TYPE_IMAGE_GIF:
        shareIntent.setType("image/gif");
        break;
    case AttachmentModel.TYPE_IMAGE_SVG:
        shareIntent.setType("image/svg+xml");
        break;
    case AttachmentModel.TYPE_IMAGE_STATIC:
        if (extension.equalsIgnoreCase(".png")) {
            shareIntent.setType("image/png");
        } else if (extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".jpg")) {
            shareIntent.setType("image/jpeg");
        } else {
            shareIntent.setType("image/*");
        }
        break;
    case AttachmentModel.TYPE_VIDEO:
        if (extension.equalsIgnoreCase(".mp4")) {
            shareIntent.setType("video/mp4");
        } else if (extension.equalsIgnoreCase(".webm")) {
            shareIntent.setType("video/webm");
        } else if (extension.equalsIgnoreCase(".avi")) {
            shareIntent.setType("video/avi");
        } else if (extension.equalsIgnoreCase(".mov")) {
            shareIntent.setType("video/quicktime");
        } else if (extension.equalsIgnoreCase(".mkv")) {
            shareIntent.setType("video/x-matroska");
        } else if (extension.equalsIgnoreCase(".flv")) {
            shareIntent.setType("video/x-flv");
        } else if (extension.equalsIgnoreCase(".wmv")) {
            shareIntent.setType("video/x-ms-wmv");
        } else {
            shareIntent.setType("video/*");
        }
        break;
    case AttachmentModel.TYPE_AUDIO:
        if (extension.equalsIgnoreCase(".mp3")) {
            shareIntent.setType("audio/mpeg");
        } else if (extension.equalsIgnoreCase(".mp4")) {
            shareIntent.setType("audio/mp4");
        } else if (extension.equalsIgnoreCase(".ogg")) {
            shareIntent.setType("audio/ogg");
        } else if (extension.equalsIgnoreCase(".webm")) {
            shareIntent.setType("audio/webm");
        } else if (extension.equalsIgnoreCase(".flac")) {
            shareIntent.setType("audio/flac");
        } else if (extension.equalsIgnoreCase(".wav")) {
            shareIntent.setType("audio/vnd.wave");
        } else {
            shareIntent.setType("audio/*");
        }
        break;
    case AttachmentModel.TYPE_OTHER_FILE:
        shareIntent.setType("application/octet-stream");
        break;
    }
    Logger.d(TAG, shareIntent.getType());
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tag.file));
    startActivity(Intent.createChooser(shareIntent, getString(R.string.share_via)));
}

From source file:com.grass.caishi.cc.activity.SettingUserActivity.java

/**
 * ?//  ww  w  .ja  va  2  s  . co  m
 */
public void selectPicFromCamera() {

    // cameraFile = new File(PathUtil.getInstance().getImagePath(),
    // DemoApplication.getInstance().getUserName()

    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(cameraFile)), USERPIC_REQUEST_CODE_CAMERA);
}

From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //Log.d("AlerteVoirie_PM", "Result : " + requestCode);
    switch (requestCode) {
    case R.id.existing_incidents_add_picture:
    case R.id.ImageView_far:
    case R.id.ImageView_close:
        if (resultCode == RESULT_OK) {
            try {

                String finalPath;

                if (data != null) {
                    Uri path = data.getData();
                    // OI FILE Manager
                    String filemanagerString = path.getPath();
                    // MEDIA GALLERY
                    String selectedImagePath = getPath(path);

                    if (selectedImagePath != null) {
                        finalPath = selectedImagePath;
                        System.out.println("selectedImagePath is the right one for you! " + finalPath);
                    } else {
                        finalPath = filemanagerString;
                        System.out.println("filemanagerstring is the right one for you!" + finalPath);
                    }//from  w ww .java 2 s.com
                    // boolean isImage = true;
                } else {
                    finalPath = uriOfPicFromCamera.getPath();
                }

                // if (data == null || getMimeType(finalPath).startsWith("image")) {
                InputStream in;
                BitmapFactory.Options opt = new BitmapFactory.Options();

                // get the sample size to have a smaller image
                in = getContentResolver().openInputStream(Uri.fromFile(new File(finalPath)));
                opt.inSampleSize = getSampleSize(
                        getContentResolver().openInputStream(Uri.fromFile(new File(finalPath))));
                in.close();

                // decode a sampled version of the picture
                in = getContentResolver().openInputStream(Uri.fromFile(new File(finalPath)));
                Bitmap picture = BitmapFactory.decodeStream(in, null, opt);

                // Bitmap picture = BitmapFactory.decodeFile(finalPath);
                in.close();

                File f = new File(uriOfPicFromCamera.getPath());
                f.delete();

                // save the new image
                String pictureName = requestCode == R.id.ImageView_close ? CAPTURE_CLOSE : CAPTURE_FAR;
                FileOutputStream fos = openFileOutput(pictureName, MODE_PRIVATE);

                picture.compress(CompressFormat.JPEG, 80, fos);
                fos.close();

                if (requestCode == R.id.ImageView_far || mAdditionalImageType == ADDITIONAL_IMAGE_TYPE_FAR) {
                    loadZoom();
                } else if (mAdditionalImageType == ADDITIONAL_IMAGE_TYPE_CLOSE) {
                    File img = new File(getFilesDir() + "/" + CAPTURE_FAR);
                    mCurrentAction = ACTION_ADD_IMAGE;
                    timeoutHandler.postDelayed(timeout, TIMEOUT);
                    AVService.getInstance(this).postImage(this, Utils.getUdid(this), "",
                            Long.toString(currentIncident.id), null, img, false);
                }

                if (requestCode != R.id.existing_incidents_add_picture) {
                    setPictureToImageView(pictureName, (ImageView) findViewById(requestCode));
                }

                if (requestCode == R.id.ImageView_far
                        && ((TextView) findViewById(R.id.TextView_address)).getText().length() > 0) {
                    ((Button) findViewById(R.id.Button_validate)).setEnabled(true);
                }
                // }

                // FileOutputStream fos = openFileOutput("capture", MODE_WORLD_READABLE);
                // InputStream in = getContentResolver().openInputStream(uriOfPicFromCamera);
                // Utils.fromInputToOutput(in, fos);
                // fos.close();
                // in.close();

                mAdditionalImageType = 0;
            } catch (FileNotFoundException e) {
                Log.e("AlerteVoirie_PM", "", e);
            } catch (IOException e) {
                Log.e("AlerteVoirie_PM", "", e);
            } catch (NullPointerException e) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog alert;
                builder.setMessage("Image invalide").setCancelable(false).setPositiveButton("Ok", null);
                alert = builder.create();
                alert.show();
            }

        } else if (resultCode == RESULT_CANCELED) {
            if (uriOfPicFromCamera != null) {
                File tmpFile = new File(uriOfPicFromCamera.getPath());
                tmpFile.delete();
                uriOfPicFromCamera = null;
            }
        }
        break;

    case REQUEST_CATEGORY:
        if (resultCode == RESULT_OK) {
            setCategory(data.getLongExtra(IntentData.EXTRA_CATEGORY_ID, -1));
            // TODO do this when update request ready
            findViewById(R.id.Button_validate).setVisibility(View.VISIBLE);
        }
        break;
    case REQUEST_POSITION:
        if (resultCode == RESULT_OK) {
            currentIncident.address = data.getStringExtra(IntentData.EXTRA_ADDRESS);
            currentIncident.longitude = data.getDoubleExtra(IntentData.EXTRA_LONGITUDE, 0);
            currentIncident.latitude = data.getDoubleExtra(IntentData.EXTRA_LATITUDE, 0);
            ((TextView) findViewById(R.id.TextView_address)).setText(currentIncident.address);
            if (currentIncident.address != null && currentIncident.address.length() > 0 && canvalidate) {
                ((Button) findViewById(R.id.Button_validate)).setEnabled(true);
            }
            findViewById(R.id.Button_validate).setVisibility(View.VISIBLE);
        }
        break;
    case REQUEST_COMMENT:
        if (resultCode == RESULT_OK) {
            currentIncident.description = data.getStringExtra(IntentData.EXTRA_COMMENT);
            ((TextView) findViewById(R.id.TextView_comment)).setText(currentIncident.description);
            if (currentIncident.description != null)
                findViewById(R.id.TextView_nocomment).setVisibility(View.GONE);
            // findViewById(R.id.Button_validate).setVisibility(View.VISIBLE);
        }
        break;
    case REQUEST_IMAGE_COMMENT:
        if (resultCode == RESULT_OK) {
            showDialog(DIALOG_PROGRESS);
            File img = new File(getFilesDir() + "/arrowed.jpg");
            mCurrentAction = ACTION_ADD_IMAGE;
            timeoutHandler.postDelayed(timeout, TIMEOUT);
            AVService.getInstance(this).postImage(this, Utils.getUdid(this),
                    data.getStringExtra(IntentData.EXTRA_COMMENT), Long.toString(currentIncident.id), img, null,
                    false);
        }
        break;
    case REQUEST_COMMENT_BEFORE_EXIT:
        if (resultCode == RESULT_OK) {
            currentIncident.description = data.getStringExtra(IntentData.EXTRA_COMMENT);
            ((TextView) findViewById(R.id.TextView_comment)).setText(currentIncident.description);
            postNewIncident();
        }
        break;
    case REQUEST_DETAILS:
        if (resultCode == RESULT_OK) {
            // startActivityForResult(data, requestCode)

            if (mCurrentAction == ACTION_ADD_IMAGE) {
                Intent i = new Intent(getApplicationContext(), AddCommentActivity.class);
                startActivityForResult(i, REQUEST_IMAGE_COMMENT);
            } else {
                // set new img
                setPictureToImageView("arrowed.jpg", (ImageView) findViewById(R.id.ImageView_far));
                loadComment(REQUEST_COMMENT);
            }

        }
        break;
    default:
        super.onActivityResult(requestCode, resultCode, data);
        break;
    }
}

From source file:org.droidpres.activity.TransferActivity.java

private void updateApp() {
    new AlertDialog.Builder(this).setMessage(R.string.msg_UpdateApk)
            .setTitle(android.R.string.dialog_alert_title)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    File apkFile = new File(SetupRootActivity.getApkFileName());
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    startActivity(intent);
                }/*from ww w.j a va 2s.c om*/
            }).setCancelable(false).show();
}

From source file:com.grass.caishi.cc.activity.SettingUserActivity.java

/**
 * onActivityResult/*  ww w  .  j a v  a  2 s  . c om*/
 */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == USERPIC_REQUEST_CODE_CAMERA) { // ?
        if (cameraFile != null && cameraFile.exists()) {
            Log.d("cameraFile" + cameraFile.getAbsolutePath());
            // ?uri imageUri = Uri.fromFile(cameraFile);
            cropImageUri(Uri.fromFile(cameraFile), 300, 300, USERPIC_REQUEST_CODE_CUT);

        }
    } else if (requestCode == USERPIC_REQUEST_CODE_LOCAL) { // ?
        if (data != null) {
            Uri selectedImage = data.getData();
            if (selectedImage != null) {
                cropImageUri(selectedImage, 300, 300, USERPIC_REQUEST_CODE_CUT);
                // Log.d("log","selectedImage"+selectedImage);

            }
        }
    } else if (requestCode == USERPIC_REQUEST_CODE_CUT) {// ?
        // ?
        if (data != null) {
            Bitmap bitmap = data.getParcelableExtra("data");
            iv_user_photo.setImageBitmap(bitmap);

            File file = saveJPGE_After(bitmap, cameraFile); // ????

            RequestParams params = new RequestParams();
            if (file.exists()) {
                try {
                    dialog.show();
                    params.put("logo", file, "image/jpeg");
                    // params.put("user",
                    // MyApplication.getInstance().getUser());
                    params.put("type", "logo");
                    // params.add("uid", uid);
                    HttpRestClient.post(Constant.UPDATE_USER_INFO_DO, params, responseHandler);

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                Toast toast = Toast.makeText(this, "?SD??",
                        Toast.LENGTH_SHORT);
            }

        } else {
            // Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data);

        }
    } else if (resultCode == MainActivity.MAIN_MESSAGE_LOGIN_OUT) {
        setResult(resultCode);
        finish();
    }
}

From source file:info.papdt.blacklight.support.Utility.java

/** Create a file Uri for saving an image*/
public static Uri getOutputMediaFileUri() {
    Uri uri = Uri.fromFile(getOutputImageFile());
    lastPicPath = uri.getPath();/* w  w w  .  j av a  2s  .co  m*/
    return uri;
}

From source file:com.dwdesign.tweetings.fragment.UserProfileFragment.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
    if (intent == null)
        return;//from w ww .  jav  a2 s .  c  o  m
    switch (requestCode) {
    case REQUEST_TAKE_PHOTO: {
        if (resultCode == Activity.RESULT_OK) {
            final String path = mImageUri.getPath();
            final File file = path != null ? new File(path) : null;
            if (file != null && file.exists()) {
                mService.updateProfileImage(mUser.getId(), mImageUri, true);
            }
        }
        break;
    }
    case REQUEST_BANNER_TAKE_PHOTO: {
        if (resultCode == Activity.RESULT_OK) {
            final String path = mImageUri.getPath();
            final File file = path != null ? new File(path) : null;
            if (file != null && file.exists()) {
                mService.updateBannerImage(mUser.getId(), mImageUri, true);
            }
        }
        break;
    }
    case REQUEST_PICK_IMAGE: {
        if (resultCode == Activity.RESULT_OK && intent != null) {
            final Uri uri = intent.getData();
            final String image_path = getImagePathFromUri(getActivity(), uri);
            final File file = image_path != null ? new File(image_path) : null;
            if (file != null && file.exists()) {
                mService.updateProfileImage(mUser.getId(), Uri.fromFile(file), false);
            }
        }
        break;
    }
    case REQUEST_BANNER_PICK_IMAGE: {
        if (resultCode == Activity.RESULT_OK && intent != null) {
            final Uri uri = intent.getData();
            final String image_path = getImagePathFromUri(getActivity(), uri);
            final File file = image_path != null ? new File(image_path) : null;
            if (file != null && file.exists()) {
                mService.updateBannerImage(mUser.getId(), Uri.fromFile(file), false);
            }
        }
        break;
    }
    case REQUEST_SET_COLOR: {
        if (resultCode == Activity.RESULT_OK && intent != null) {
            final int color = intent.getIntExtra(Accounts.USER_COLOR, Color.TRANSPARENT);
            setUserColor(getActivity(), mUserId, color);
            updateUserColor();
        }
        break;
    }
    }

}

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode != RESULT_OK) {
        return;//from  ww w.j ava2s. c  om
    } 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);
        if (isslinece) {
            MyImageLoader.displayDefaultImage("file://" + photoUri.getPath(), slience_image);
            zhizhao_path = photoUri.toString();
            try {
                upLoadImage(new File((new URI(photoUri.toString()))), "BusinessLicense");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } else if (isZhengshu) {
            MyImageLoader.displayDefaultImage("file://" + photoUri.getPath(), zhengshu_iamge);
            xukezheng_path = photoUri.toString();
            try {
                upLoadImage(new File((new URI(photoUri.toString()))), "LicenseKey");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } else if (isheadImage) {
            MyImageLoader.displayDefaultImage("file://" + photoUri.getPath(), head_image);
            tuoxiang_path = photoUri.toString();
            try {
                upLoadImage(new File((new URI(photoUri.toString()))), "Photo");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            //upLoadImage(new File((new URI(photoUri.toString()))), "Photo");
        } else if (isItem) {
            if (imagePath.size() + images.size() < 10) {
                shangpu_path.add(photoUri.toString());
                try {
                    upLoadImage(new File((new URI(photoUri.toString()))), "Seller");
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                //imagePath.add(photoUri.getPath());
            } else {
                Toast.makeText(BusinessMyCenterActivity.this, "?9",
                        Toast.LENGTH_SHORT).show();
            }
        }
        //addImage(imagePath);
    }
}