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:com.gimranov.zandy.app.AttachmentActivity.java

private void showAttachment(Attachment att) {
    if (att.status == Attachment.LOCAL) {
        Log.d(TAG, "Starting to display local attachment");
        Uri uri = Uri.fromFile(new File(att.filename));
        String mimeType = att.content.optString("mimeType", "application/pdf");
        try {/*from  ww w .ja  v  a2s  . c  om*/
            startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType(uri, mimeType));
        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "No activity for intent", e);
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.attachment_intent_failed, mimeType), Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

/**
 * loads poiInformation and returns them as JSONArray. Ensure attributeNames of JSON POIs are well known in JavaScript, so you can parse them easily
 * @param userLocation the location of the user
 * @return POI information in JSONArray/*  ww  w.jav a  2s.c  o  m*/
 */
public JSONArray getPoiInformation(final Location userLocation, String kmlPath) {

    if (userLocation == null) {
        return null;
    }

    ArrayList<KmlParser.Place> places = new ArrayList<>();
    try {
        ContentResolver cr = getApplicationContext().getContentResolver();
        InputStream is = cr.openInputStream(Uri.fromFile(new File(kmlPath)));
        places = new KmlParser().parse(is);
    } catch (final Exception e) {
        AbstractArchitectCamActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(AbstractArchitectCamActivity.this, "Invalid kml file \n" + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    final JSONArray pois = new JSONArray();

    // ensure these attributes are also used in JavaScript when extracting POI data
    final String ATTR_ID = "id";
    final String ATTR_NAME = "name";
    final String ATTR_DESCRIPTION = "description";
    final String ATTR_LATITUDE = "latitude";
    final String ATTR_LONGITUDE = "longitude";
    final String ATTR_ALTITUDE = "altitude";
    //ArrayList<KmlParser.Place> places = getIntent().getExtras().getParcelableArrayList("places");
    for (KmlParser.Place place : places) {
        final HashMap<String, String> poiInformation = new HashMap<String, String>();
        poiInformation.put(ATTR_ID, "1");
        poiInformation.put(ATTR_NAME, place.name);
        poiInformation.put(ATTR_DESCRIPTION, place.description != null ? place.description : "");
        //double[] poiLocationLatLon = getRandomLatLonNearby(userLocation.getLatitude(), userLocation.getLongitude());
        poiInformation.put(ATTR_LATITUDE, place.lat);
        poiInformation.put(ATTR_LONGITUDE, place.lon);
        final float UNKNOWN_ALTITUDE = -32768f; // equals "AR.CONST.UNKNOWN_ALTITUDE" in JavaScript (compare AR.GeoLocation specification)
        // Use "AR.CONST.UNKNOWN_ALTITUDE" to tell ARchitect that altitude of places should be on user level. Be aware to handle altitude properly in locationManager in case you use valid POI altitude value (e.g. pass altitude only if GPS accuracy is <7m).
        poiInformation.put(ATTR_ALTITUDE, String.valueOf(UNKNOWN_ALTITUDE));
        pois.put(new JSONObject(poiInformation));
    }

    return pois;
}

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

/**
 * ?/*  www. j av a  2  s . c  om*/
 */
public void selectPicFromCamera() {
    if (!CommonUtils.isExitsSdcard()) {
        Toast.makeText(getApplicationContext(), "SD????", Toast.LENGTH_SHORT).show();
        return;
    }

    // cameraFile = new File(PathUtil.getInstance().getImagePath(),
    // DemoApplication.getInstance().getUserName()
    cameraFile = new File(PathUtil.getInstance().getImagePath(),
            MyApplication.getInstance().getUser() + System.currentTimeMillis() + ".jpg");
    cameraFile.getParentFile().mkdirs();
    startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(cameraFile)), REQUEST_CODE_CAMERA);
}

From source file:net.bytten.comicviewer.ComicViewerActivity.java

public void shareComicImage() {
    if (comicInfo == null || comicInfo.getImage() == null) {
        toast("No image loaded.");
        return;//from  w w  w. ja va  2s.  c o m
    }

    new Utility.CancellableAsyncTaskWithProgressDialog<Uri, File>(getStringAppName()) {
        Throwable e;

        @Override
        protected File doInBackground(Uri... params) {
            try {
                File file = new File(getApplicationContext().getExternalCacheDir(),
                        comicDef.getComicTitleAbbrev() + "-" + params[0].getLastPathSegment());
                Utility.blockingSaveFile(file, params[0]);
                return file;

            } catch (InterruptedException ex) {
                return null;
            } catch (Throwable ex) {
                e = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            super.onPostExecute(result);
            if (result != null && e == null) {

                try {
                    Uri uri = Uri.fromFile(result);
                    Intent intent = new Intent(Intent.ACTION_SEND, null);
                    intent.setType(Utility.getContentType(uri));
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(intent, "Share image..."));
                    return;
                } catch (MalformedURLException ex) {
                    e = ex;
                } catch (IOException ex) {
                    e = ex;
                }
            }
            e.printStackTrace();
            failed("Couldn't save attachment: " + e);
        }

    }.start(this, "Saving image...", new Uri[] { comicInfo.getImage() });
}

From source file:edu.mit.mobile.android.locast.sync.AbsMediaSync.java

/**
 * updates the metadata stored at castMediaUri with information about the local file.
 *
 * @param castMediaUri//from  w  ww.ja  v a2s.c o  m
 *            a castMedia item pointing to the metadata for the media
 * @param localFile
 *            the local copy of the media file
 * @param localThumbnail
 *            an image file representing media stored at localFile or null if there is none
 */
private void updateLocalFile(Uri castMediaUri, File localFile, File localThumbnail) {
    final ContentValues cv = new ContentValues();
    cv.put(CastMedia.COL_LOCAL_URL, Uri.fromFile(localFile).toString());
    if (localThumbnail != null) {
        cv.put(CastMedia.COL_THUMB_LOCAL, Uri.fromFile(localFile).toString());
    }
    cv.put(JsonSyncableItem.COL_DIRTY, SyncableProvider.FLAG_DO_NOT_CHANGE_DIRTY);

    getContentResolver().update(castMediaUri, cv, null, null);

}

From source file:es.upv.riromu.arbre.main.MainActivity.java

/******************************************/
public void captureImage(View view) {
    try {//from w ww. jav a2s  .  c o  m
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
                //
                image_uri = Uri.fromFile(photoFile);
            } catch (IOException ex) {
                // Error occurred while creating the File
                Log.i(TAG, "Error");
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
                takePictureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
                        getResources().getConfiguration().orientation);
                //    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,uriSavedImage);
                startActivityForResult(takePictureIntent, CAPTURE_IMAGE);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error" + e.getMessage());
    }
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private void cameraSucess(Intent intent) {
    try {/*from w  w w  . java 2s.  co  m*/
        Bitmap bitmap = null;
        try {
            //???imagebitmap
            if (mAllowEdit) {
                //??????Android???
                //???URI
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    bitmap = extras.getParcelable("data");
                }

                //?????URI
                if ((bitmap == null) || (extras == null)) {
                    bitmap = getCroppedBitmap(intent);
                }
            } else { // ????
                bitmap = android.provider.MediaStore.Images.Media.getBitmap(getContext().getContentResolver(),
                        mImageUri);
            }
        } catch (FileNotFoundException e) {
            Uri uri = intent.getData();
            android.content.ContentResolver resolver = getContext().getContentResolver();
            bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
        } catch (IOException e) {
            mCallbackCtx.error("Can't open image");
        } catch (OutOfMemoryError e) {
            XNotification notification = new XNotification(mExtensionContext.getSystemContext());
            notification.alert("Size of Image is too large!", "Save Image Error", "OK", null, DURATION);
            mCallbackCtx.error("Size of image is too large");
            return;
        }

        // ???
        Bitmap scaleBitmap = scaleBitmap(bitmap);
        Uri uri = null;
        if (mDestType == DATA_URL) {
            processPicture(scaleBitmap);
            checkForDuplicateImage(DATA_URL);
        } else if (mDestType == FILE_URI || mDestType == NATIVE_URI) {
            if (!this.mSaveToPhotoAlbum) {
                String suffixName = null;
                if (mEncodingType == JPEG) {
                    suffixName = ".jpg";
                } else if (mEncodingType == PNG) {
                    suffixName = ".png";
                } else {
                    throw new IllegalArgumentException("Invalid Encoding Type: " + mEncodingType);
                }
                String photoName = System.currentTimeMillis() + suffixName;
                uri = Uri.fromFile(new File(mWebContext.getWorkSpace(), photoName));
            } else {
                uri = getUriFromMediaStore();
            }
            if (uri == null) {
                mCallbackCtx.error("Error capturing image - no media storage found.");
            }

            // ?
            OutputStream os = getContext().getContentResolver().openOutputStream(uri);
            scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
            os.close();

            // ??success callback
            XPathResolver pathResolver = new XPathResolver(uri.toString(), "", getContext());
            mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve());
        }
        scaleBitmap.recycle();
        scaleBitmap = null;
        cleanup(FILE_URI, mImageUri, uri, bitmap);
    } catch (IOException e) {
        mCallbackCtx.error("Error capturing image.");
    }
}

From source file:com.example.zf_android.activity.MerchantEdit.java

private void show3Dialog(int type, final String uri) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MerchantEdit.this);
    final String[] items = getResources().getStringArray(R.array.apply_detail_view);

    MerchantEdit.this.type = type;
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override//from  w  ww .ja  v a 2s .  c o m
        public void onClick(DialogInterface dialog, int which) {

            switch (which) {
            case 0: {

                AlertDialog.Builder build = new AlertDialog.Builder(MerchantEdit.this);
                LayoutInflater factory = LayoutInflater.from(MerchantEdit.this);
                final View textEntryView = factory.inflate(R.layout.show_view, null);
                build.setView(textEntryView);
                final ImageView view = (ImageView) textEntryView.findViewById(R.id.imag);
                //               ImageCacheUtil.IMAGE_CACHE.get(uri, view);
                ImageLoader.getInstance().displayImage(uri, view, options);
                build.create().show();
                break;
            }

            case 1: {

                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                } else {
                    intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                break;
            }
            case 2: {
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File outDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                    if (!outDir.exists()) {
                        outDir.mkdirs();
                    }
                    File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                    photoPath = outFile.getAbsolutePath();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                } else {
                    CommonUtil.toastShort(MerchantEdit.this, getString(R.string.toast_no_sdcard));
                }
                break;
            }
            }
        }
    });

    builder.show();
}

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

private void openExternal() {
    GalleryItemViewTag tag = getCurrentTag();
    if (tag == null)
        return;/*w  ww.java 2s  .c  om*/
    String mime;
    switch (tag.attachmentModel.type) {
    case AttachmentModel.TYPE_VIDEO:
        mime = "video/*";
        break;
    case AttachmentModel.TYPE_AUDIO:
        mime = "audio/*";
        break;
    default:
        mime = "*/*";
        break;
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(tag.file), mime);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode != RESULT_OK) {
        return;//from   w ww .ja  v  a 2s  .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);
        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();
            }

            //upLoadImage(new File((new URI(photoUri.toString()))), "Photo");
        } else if (isItem) {
            if (images.size() < 10) {
                shangpu_path.add(photoUri.toString());
                try {
                    upLoadImage(new File((new URI(photoUri.toString()))), "Seller");
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(FourStepRegisterActivity.this, "?9",
                        Toast.LENGTH_SHORT).show();
            }
        }
        //addImage(imagePath);
    }
}