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.remobile.file.LocalFilesystem.java

@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary)
        throws IOException, NoModificationAllowedException {

    boolean append = false;
    if (offset > 0) {
        this.truncateFileAtURL(inputURL, offset);
        append = true;//from   w w  w.ja  v a 2s.  c  o m
    }

    byte[] rawData;
    if (isBinary) {
        rawData = Base64.decode(data, Base64.DEFAULT);
    } else {
        rawData = data.getBytes();
    }
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    try {
        byte buff[] = new byte[rawData.length];
        String absolutePath = filesystemPathForURL(inputURL);
        FileOutputStream out = new FileOutputStream(absolutePath, append);
        try {
            in.read(buff, 0, buff.length);
            out.write(buff, 0, rawData.length);
            out.flush();
        } finally {
            // Always close the output
            out.close();
        }
        if (isPublicDirectory(absolutePath)) {
            broadcastNewFile(Uri.fromFile(new File(absolutePath)));
        }
    } catch (NullPointerException e) {
        // This is a bug in the Android implementation of the Java Stack
        NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
        throw realException;
    }

    return rawData.length;
}

From source file:com.remobile.camera.CameraLauncher.java

/**
 * Brings up the UI to perform crop on passed image URI
 *
 * @param picUri/* www .jav a  2  s  .  com*/
 */
private void performCrop(Uri picUri, int destType, Intent cameraIntent) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties
        cropIntent.putExtra("crop", "true");

        // indicate output X and Y
        if (targetWidth > 0) {
            cropIntent.putExtra("outputX", targetWidth);
        }
        if (targetHeight > 0) {
            cropIntent.putExtra("outputY", targetHeight);
        }
        if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
        }
        // create new file handle to get full resolution crop
        croppedUri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        cropIntent.putExtra("output", croppedUri);

        // start the activity - we handle returning in onActivityResult

        if (this.cordova != null) {
            this.cordova.startActivityForResult((CordovaPlugin) this, cropIntent, CROP_CAMERA + destType);
        }
    } catch (ActivityNotFoundException anfe) {
        Log.e(LOG_TAG, "Crop operation not supported on this device");
        try {
            processResultFromCamera(destType, cameraIntent);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, "Unable to write to file");
        }
    }
}

From source file:com.tuxpan.foregroundcameragalleryplugin.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//from   w ww  .  jav  a  2s.  c  o  m
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
                    if (bitmap == null) {
                        // Try to get the bitmap from intent.
                        bitmap = (Bitmap) intent.getExtras().get("data");
                    }

                    // Double-check the bitmap.
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI || destType == NATIVE_URI) {
                    if (this.saveToPhotoAlbum) {
                        Uri inputUri = getUriFromMediaStore();
                        //Just because we have a media URI doesn't mean we have a real file, we need to make it
                        uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
                    } else {
                        uri = Uri.fromFile(
                                new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && !this.correctOrientation) {
                        writeUncompressedImage(uri);

                        this.callbackContext.success(uri.toString());
                    } else {
                        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileHelper.getRealPath(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.callbackContext.success(uri.toString());
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.callbackContext.success(uri.toString());
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating, nor compressing needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1
                        && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
                    this.callbackContext.success(uri.toString());
                } else {
                    String uriString = uri.toString();
                    // Get the path to the image. Makes loading so much easier.
                    String mimeType = FileHelper.getMimeType(uriString, this.cordova);
                    // If we don't have a valid image so quit.
                    if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retrieve path to picture!");
                        return;
                    }
                    Bitmap bitmap = null;
                    try {
                        bitmap = getScaledBitmap(uriString);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        rotate = getImageOrientation(uri);
                        if (rotate != 0) {
                            //                                Matrix matrix = new Matrix();
                            //                                matrix.setRotate(rotate);
                            //                                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                            RotateTask r = new RotateTask(bitmap, srcType, destType, rotate, intent);
                            r.execute();
                            return;
                        }
                    }
                    returnImageToProcess(bitmap, srcType, destType, intent, rotate);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:babybear.akbquiz.ConfigActivity.java

/**
 * /*  ww w  .j  av  a2s .  c  om*/
 */
protected void customBgImage() {
    DisplayMetrics dm = getResources().getDisplayMetrics();
    int width = dm.widthPixels;
    int height = dm.heightPixels;

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
    intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*"); // 
    intent.putExtra("crop", "circle"); // ?
    intent.putExtra("aspectX", width); // ? 
    intent.putExtra("aspectY", height); // ? .
    intent.putExtra("output", Uri.fromFile(customBgImage));// 
    intent.putExtra("outputFormat", "PNG");// ?
    intent.putExtra("noFaceDetection", true); // ?
    intent.putExtra("return-data", false); // ??Intent
    startActivityForResult(intent, REQUESTCODE_IMAGE);
}

From source file:com.matthewmitchell.peercoin_android_wallet.ui.WalletActivity.java

public void handleExportTransactions() {

    // Create CSV file from transactions

    final File file = new File(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR,
            Constants.Files.TX_EXPORT_NAME + "-" + getFileDate() + ".csv");

    try {/* w  ww. ja  v a  2 s  .  c  o m*/

        final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.append("Date,Label,Amount (" + MonetaryFormat.CODE_PPC + "),Fee (" + MonetaryFormat.CODE_PPC
                + "),Address,Transaction Hash,Confirmations\n");

        if (txListAdapter == null || txListAdapter.transactions.isEmpty()) {
            longToast(R.string.export_transactions_mail_intent_failed);
            log.error("exporting transactions failed");
            return;
        }

        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm z");
        dateFormat.setTimeZone(TimeZone.getDefault());

        for (Transaction tx : txListAdapter.transactions) {

            TransactionsListAdapter.TransactionCacheEntry txCache = txListAdapter.getTxCache(tx);
            String memo = tx.getMemo() == null ? "" : StringEscapeUtils.escapeCsv(tx.getMemo());
            String fee = tx.getFee() == null ? "" : tx.getFee().toPlainString();
            String address = txCache.address == null ? getString(R.string.export_transactions_unknown)
                    : txCache.address.toString();

            writer.append(dateFormat.format(tx.getUpdateTime()) + ",");
            writer.append(memo + ",");
            writer.append(txCache.value.toPlainString() + ",");
            writer.append(fee + ",");
            writer.append(address + ",");
            writer.append(tx.getHash().toString() + ",");
            writer.append(tx.getConfidence().getDepthInBlocks() + "\n");

        }

        writer.flush();
        writer.close();

    } catch (IOException x) {
        longToast(R.string.export_transactions_mail_intent_failed);
        log.error("exporting transactions failed", x);
        return;
    }

    final DialogBuilder dialog = new DialogBuilder(this);
    dialog.setMessage(Html.fromHtml(getString(R.string.export_transactions_dialog_success, file)));

    dialog.setPositiveButton(WholeStringBuilder.bold(getString(R.string.export_keys_dialog_button_archive)),
            new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {

                    final Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_transactions_mail_subject));
                    intent.putExtra(Intent.EXTRA_TEXT,
                            makeEmailText(getString(R.string.export_transactions_mail_text)));
                    intent.setType(Constants.MIMETYPE_TX_EXPORT);
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));

                    try {
                        startActivity(Intent.createChooser(intent,
                                getString(R.string.export_transactions_mail_intent_chooser)));
                        log.info("invoked chooser for exporting transactions");
                    } catch (final Exception x) {
                        longToast(R.string.export_transactions_mail_intent_failed);
                        log.error("exporting transactions failed", x);
                    }

                }

            });

    dialog.setNegativeButton(R.string.button_dismiss, null);
    dialog.show();

}

From source file:info.guardianproject.gpg.KeyListFragment.java

private void keyserverOperation(final int operation, final ActionMode mode) {
    new AsyncTask<Void, Void, Void>() {
        final Context context = getActivity().getApplicationContext();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER,
                "ipv4.pool.sks-keyservers.net");
        final long[] selected = mListView.getCheckedItemIds();
        final Intent intent = new Intent(context, ImportFileActivity.class);

        @Override/* w  w w.ja  va2s.  c om*/
        protected Void doInBackground(Void... params) {
            HkpKeyServer keyserver = new HkpKeyServer(host);
            if (operation == DELETE_KEYS) {
                String args = "--batch --yes --delete-keys";
                for (int i = 0; i < selected.length; i++) {
                    args += " " + Long.toHexString(selected[i]);
                }
                GnuPG.gpg2(args);
            } else if (operation == KEYSERVER_SEND) {
                String args = "--keyserver " + host + " --send-keys ";
                for (int i = 0; i < selected.length; i++) {
                    args += " " + Long.toHexString(selected[i]);
                }
                // TODO this should use the Java keyserver stuff
                GnuPG.gpg2(args);
            } else if (operation == KEYSERVER_RECEIVE) {
                String keys = "";
                for (int i = 0; i < selected.length; i++) {
                    try {
                        keys += keyserver.get(selected[i]);
                        keys += "\n\n";
                    } catch (QueryException e) {
                        e.printStackTrace();
                    }
                }
                // An Intent can carry very much data, so write it
                // to a cached file
                try {
                    File privateFile = File.createTempFile("keyserver", ".pkr", mCurrentActivity.getCacheDir());
                    FileUtils.writeStringToFile(privateFile, keys);
                    intent.setType(getString(R.string.pgp_keys));
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(privateFile));
                } catch (IOException e) {
                    e.printStackTrace();
                    // try sending the key data inline in the Intent
                    intent.setType("text/plain");
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, keys);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            GpgApplication.triggerContactsSync();
            mCurrentActivity.setSupportProgressBarIndeterminateVisibility(false);
            mode.finish(); // Action picked, so close the CAB
            if (operation == KEYSERVER_RECEIVE)
                startActivity(intent);
        }
    }.execute();
}

From source file:it.feio.android.omninotes.async.DataBackupIntentService.java

/**
  * Imports notes and notebooks from Springpad exported archive
  */*from  w w w . ja  va 2s .  c  om*/
  * @param intent
  */
synchronized private void importDataFromSpringpad(Intent intent) {
    String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP);
    Importer importer = new Importer();
    try {
        importer.setZipProgressesListener(percentage -> mNotificationsHelper
                .setMessage(getString(R.string.extracted) + " " + percentage + "%").show());
        importer.doImport(backupPath);
        // Updating notification
        updateImportNotification(importer);
    } catch (ImportException e) {
        new NotificationsHelper(this).createNotification(R.drawable.ic_emoticon_sad_white_24dp,
                getString(R.string.import_fail) + ": " + e.getMessage(), null).setLedActive().show();
        return;
    }
    List<SpringpadElement> elements = importer.getSpringpadNotes();

    // If nothing is retrieved it will exit
    if (elements == null || elements.size() == 0) {
        return;
    }

    // These maps are used to associate with post processing notes to categories (notebooks)
    HashMap<String, Category> categoriesWithUuid = new HashMap<>();

    // Adds all the notebooks (categories)
    for (SpringpadElement springpadElement : importer.getNotebooks()) {
        Category cat = new Category();
        cat.setName(springpadElement.getName());
        cat.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
        DbHelper.getInstance().updateCategory(cat);
        categoriesWithUuid.put(springpadElement.getUuid(), cat);

        // Updating notification
        importedSpringpadNotebooks++;
        updateImportNotification(importer);
    }
    // And creates a default one for notes without notebook 
    Category defaulCategory = new Category();
    defaulCategory.setName("Springpad");
    defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
    DbHelper.getInstance().updateCategory(defaulCategory);

    // And then notes are created
    Note note;
    Attachment mAttachment = null;
    Uri uri;
    for (SpringpadElement springpadElement : importer.getNotes()) {
        note = new Note();

        // Title
        note.setTitle(springpadElement.getName());

        // Content dependent from type of Springpad note
        StringBuilder content = new StringBuilder();
        content.append(
                TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement.getText()));
        content.append(
                TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement.getDescription());

        // Some notes could have been exported wrongly
        if (springpadElement.getType() == null) {
            Toast.makeText(this, getString(R.string.error), Toast.LENGTH_SHORT).show();
            continue;
        }

        if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) {
            try {
                content.append(System.getProperty("line.separator"))
                        .append(springpadElement.getVideos().get(0));
            } catch (IndexOutOfBoundsException e) {
                content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
            }
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) {
            content.append(System.getProperty("line.separator"))
                    .append(TextUtils.join(", ", springpadElement.getCast()));
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) {
            content.append(System.getProperty("line.separator")).append("Author: ")
                    .append(springpadElement.getAuthor()).append(System.getProperty("line.separator"))
                    .append("Publication date: ").append(springpadElement.getPublicationDate());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) {
            content.append(System.getProperty("line.separator")).append("Ingredients: ")
                    .append(springpadElement.getIngredients()).append(System.getProperty("line.separator"))
                    .append("Directions: ").append(springpadElement.getDirections());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) {
            content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS)
                && springpadElement.getPhoneNumbers() != null) {
            content.append(System.getProperty("line.separator")).append("Phone number: ")
                    .append(springpadElement.getPhoneNumbers().getPhone());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) {
            content.append(System.getProperty("line.separator")).append("Category: ")
                    .append(springpadElement.getCategory()).append(System.getProperty("line.separator"))
                    .append("Manufacturer: ").append(springpadElement.getManufacturer())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) {
            content.append(System.getProperty("line.separator")).append("Wine type: ")
                    .append(springpadElement.getWine_type()).append(System.getProperty("line.separator"))
                    .append("Varietal: ").append(springpadElement.getVarietal())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) {
            content.append(System.getProperty("line.separator")).append("Artist: ")
                    .append(springpadElement.getArtist());
        }
        for (SpringpadComment springpadComment : springpadElement.getComments()) {
            content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter())
                    .append(" commented at 0").append(springpadComment.getDate()).append(": ")
                    .append(springpadElement.getArtist());
        }

        note.setContent(content.toString());

        // Checklists
        if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) {
            StringBuilder sb = new StringBuilder();
            String checkmark;
            for (SpringpadItem mSpringpadItem : springpadElement.getItems()) {
                checkmark = mSpringpadItem.getComplete()
                        ? it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM
                        : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM;
                sb.append(checkmark).append(mSpringpadItem.getName())
                        .append(System.getProperty("line.separator"));
            }
            note.setContent(sb.toString());
            note.setChecklist(true);
        }

        // Tags
        String tags = springpadElement.getTags().size() > 0
                ? "#" + TextUtils.join(" #", springpadElement.getTags())
                : "";
        if (note.isChecklist()) {
            note.setTitle(note.getTitle() + tags);
        } else {
            note.setContent(note.getContent() + System.getProperty("line.separator") + tags);
        }

        // Address
        String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress()
                : "";
        if (!TextUtils.isEmpty(address)) {
            try {
                double[] coords = GeocodeHelper.getCoordinatesFromAddress(this, address);
                note.setLatitude(coords[0]);
                note.setLongitude(coords[1]);
            } catch (IOException e) {
                Log.e(Constants.TAG,
                        "An error occurred trying to resolve address to coords during Springpad import");
            }
            note.setAddress(address);
        }

        // Reminder
        if (springpadElement.getDate() != null) {
            note.setAlarm(springpadElement.getDate().getTime());
        }

        // Creation, modification, category
        note.setCreation(springpadElement.getCreated().getTime());
        note.setLastModification(springpadElement.getModified().getTime());

        // Image
        String image = springpadElement.getImage();
        if (!TextUtils.isEmpty(image)) {
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, image);
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + image);
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // Other attachments
        for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) {
            // The attachment could be the image itself so it's jumped
            if (image != null && image.equals(springpadAttachment.getUrl()))
                continue;

            if (TextUtils.isEmpty(springpadAttachment.getUrl())) {
                continue;
            }

            // Tries first with online images
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, springpadAttachment.getUrl());
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl());
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // If the note has a category is added to the map to be post-processed
        if (springpadElement.getNotebooks().size() > 0) {
            note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0)));
        } else {
            note.setCategory(defaulCategory);
        }

        // The note is saved
        DbHelper.getInstance().updateNote(note, false);
        ReminderHelper.addReminder(OmniNotes.getAppContext(), note);

        // Updating notification
        importedSpringpadNotes++;
        updateImportNotification(importer);
    }

    // Delete temp data
    try {
        importer.clean();
    } catch (IOException e) {
        Log.w(Constants.TAG, "Springpad import temp files not deleted");
    }

    String title = getString(R.string.data_import_completed);
    String text = getString(R.string.click_to_refresh_application);
    createNotification(intent, this, title, text, null);
}

From source file:mp.paschalis.EditBookActivity.java

/**
 * Creates a sharing {@link Intent}.//w ww. j  av  a2  s .com
 *
 * @return The sharing intent.
 */
private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");

    String root = Environment.getExternalStorageDirectory() + ".SmartLib/Images";
    new File(root).mkdirs();

    File file = new File(root, app.selectedBook.isbn);

    try {
        FileOutputStream os = new FileOutputStream(file);
        bitmapBookCover.compress(CompressFormat.PNG, 80, os);
        os.flush();
        os.close();

        Uri uri = Uri.fromFile(file);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

    } catch (Exception e) {
        Log.e(TAG, e.getStackTrace().toString());
    }

    String bookInfo = "\n\n\n\nMy " + getString(R.string.bookInfo) + ":\n" + getString(R.string.title)
            + ": \t\t\t\t" + app.selectedBook.title + "\n" + getString(R.string.author) + ": \t\t\t"
            + app.selectedBook.authors + "\n" + getString(R.string.isbn) + ": \t\t\t\t" + app.selectedBook.isbn
            + "\n" + getString(R.string.published_) + " \t" + app.selectedBook.publishedYear + "\n"
            + getString(R.string.pages_) + " \t\t\t" + app.selectedBook.pageCount + "\n"
            + getString(R.string.isbn) + ": \t\t\t\t" + app.selectedBook.isbn + "\n"
            + getString(R.string.status) + ": \t\t\t"
            + App.getBookStatusString(app.selectedBook.status, EditBookActivity.this) + "\n\n"
            + "http://books.google.com/books?vid=isbn" + app.selectedBook.isbn;

    shareIntent.putExtra(Intent.EXTRA_TEXT, bookInfo);

    return shareIntent;
}

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

/**
 * updates the metadata stored at castMediaUri with information about the local file.
 *
 * @param castMediaUri/*  w w  w.j av  a2 s. c om*/
 *            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._LOCAL_URI, Uri.fromFile(localFile).toString());
    if (localThumbnail != null) {
        cv.put(CastMedia._THUMB_LOCAL, Uri.fromFile(localFile).toString());
    }
    cv.put(MediaProvider.CV_FLAG_DO_NOT_MARK_DIRTY, true);

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

}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Brings up the UI to perform crop on passed image URI
 * /*from   w  w w  .  j a  va 2  s.  c o  m*/
 * @param picUri
 */
private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties
        cropIntent.putExtra("crop", "true");
        // indicate output X and Y
        if (targetWidth > 0) {
            cropIntent.putExtra("outputX", targetWidth);
        }
        if (targetHeight > 0) {
            cropIntent.putExtra("outputY", targetHeight);
        }
        if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
        }
        // create new file handle to get full resolution crop
        croppedUri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        cropIntent.putExtra("output", croppedUri);

        // start the activity - we handle returning in onActivityResult

        if (this.activity != null) {
            this.activity.startActivityForResult(cropIntent, CROP_CAMERA);
        }
    } catch (ActivityNotFoundException anfe) {
        Log.e(LOG_TAG, "Crop operation not supported on this device");
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(picUri.toString());
    }
}