Example usage for android.support.v4.provider DocumentFile getUri

List of usage examples for android.support.v4.provider DocumentFile getUri

Introduction

In this page you can find the example usage for android.support.v4.provider DocumentFile getUri.

Prototype

public abstract Uri getUri();

Source Link

Usage

From source file:com.farmerbb.notepad.activity.MainActivity.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override//from   w  ww. j  a  v a2 s . c o  m
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {

    if (resultCode == RESULT_OK && resultData != null) {
        successful = true;

        if (requestCode == IMPORT) {
            Uri uri = resultData.getData();
            ClipData clipData = resultData.getClipData();

            if (uri != null)
                successful = importNote(uri);
            else if (clipData != null)
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    successful = importNote(clipData.getItemAt(i).getUri());
                }

            // Show toast notification
            showToast(successful
                    ? (uri == null ? R.string.notes_imported_successfully : R.string.note_imported_successfully)
                    : R.string.error_importing_notes);

            // Send broadcast to NoteListFragment to refresh list of notes
            Intent listNotesIntent = new Intent();
            listNotesIntent.setAction("com.farmerbb.notepad.LIST_NOTES");
            LocalBroadcastManager.getInstance(this).sendBroadcast(listNotesIntent);
        } else if (requestCode == EXPORT) {
            try {
                saveExportedNote(loadNote(filesToExport[fileBeingExported].toString()), resultData.getData());
            } catch (IOException e) {
                successful = false;
            }

            fileBeingExported++;
            if (fileBeingExported < filesToExport.length)
                reallyExportNotes();
            else
                showToast(successful
                        ? (fileBeingExported == 1 ? R.string.note_exported_to : R.string.notes_exported_to)
                        : R.string.error_exporting_notes);

            File fileToDelete = new File(getFilesDir() + File.separator + "exported_note");
            fileToDelete.delete();
        } else if (requestCode == EXPORT_TREE) {
            DocumentFile tree = DocumentFile.fromTreeUri(this, resultData.getData());

            for (Object exportFilename : filesToExport) {
                try {
                    DocumentFile file = tree.createFile("text/plain",
                            generateFilename(loadNoteTitle(exportFilename.toString())));

                    if (file != null)
                        saveExportedNote(loadNote(exportFilename.toString()), file.getUri());
                    else
                        successful = false;
                } catch (IOException e) {
                    successful = false;
                }
            }

            showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes);
        }
    }
}

From source file:freed.cam.apis.camera2.modules.PictureModuleApi2.java

@NonNull
private void process_rawSensor(ImageHolder image, File file) {
    Log.d(TAG, "Create DNG");

    DngCreator dngCreator = new DngCreator(cameraHolder.characteristics, image.getCaptureResult());
    //Orientation 90 is not a valid EXIF orientation value, fuck off that is valid!
    try {/*from  w  w w .  ja  v a  2  s. co  m*/
        dngCreator.setOrientation(image.captureResult.get(CaptureResult.JPEG_ORIENTATION));
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    }

    if (appSettingsManager.getApiString(AppSettingsManager.SETTING_LOCATION).equals(KEYS.ON))
        dngCreator
                .setLocation(cameraUiWrapper.getActivityInterface().getLocationHandler().getCurrentLocation());
    try {
        if (!appSettingsManager.GetWriteExternal())
            dngCreator.writeImage(new FileOutputStream(file), image.getImage());
        else {
            DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
            DocumentFile wr = df.createFile("image/*", file.getName());
            dngCreator.writeImage(
                    cameraUiWrapper.getContext().getContentResolver().openOutputStream(wr.getUri()),
                    image.getImage());
        }
        cameraUiWrapper.getActivityInterface().ScanFile(file);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    image.getImage().close();
    image = null;
}

From source file:com.osama.cryptofm.tasks.EncryptTask.java

private void encryptDocumentFile(DocumentFile file) throws FileNotFoundException {
    Log.d(TAG, "encryptDocumentFile: encrypting document file");
    if (file.isDirectory()) {
        rootDocumentFile = file;/*from   ww w .j a v a  2s  .c om*/
        for (DocumentFile f : file.listFiles()) {
            encryptDocumentFile(f);
        }
    } else {
        //check if root document is not null
        if (rootDocumentFile == null) {
            String path = mFilePaths.get(0).substring(0, mFilePaths.get(0).lastIndexOf('/'));

            Log.d(TAG, "encryptDocumentFile: Getting the root document: " + path);
            rootDocumentFile = FileDocumentUtils.getDocumentFile(new File(path));
        }
        DocumentFile temp = rootDocumentFile.createFile("pgp", file.getName() + ".pgp");
        mCreatedDocumentFiles.add(temp);
        publishProgress(file.getName(), "" + ((FileUtils.getReadableSize((file.length())))));

        InputStream in = CryptoFM.getContext().getContentResolver().openInputStream(file.getUri());
        OutputStream out = CryptoFM.getContext().getContentResolver().openOutputStream(temp.getUri());
        DocumentFileEncryption.encryptFile(in, out, pubKeyFile, true, new Date(file.lastModified()),
                file.getName());

    }
}

From source file:com.osama.cryptofm.tasks.DecryptTask.java

private void decryptDocumentFiles(DocumentFile f) throws Exception {
    Log.d(TAG, "decryptDocumentFiles: Running decryption on document file");
    //first always check if task is canceled
    if (!isCancelled()) {
        if (f.isDirectory()) {
            for (DocumentFile tmpFile : f.listFiles()) {
                decryptDocumentFiles(tmpFile);
            }//from   ww w. j av a2 s . c o m
        } else {
            File out = new File(rootPath + "/", f.getName().substring(0, f.getName().lastIndexOf('.')));
            // add the file in created files. top remove the files later of user cancels the task
            mCreatedFiles.add(out.getAbsoluteFile());
            publishProgress(f.getName(), "" + ((FileUtils.getReadableSize((f.length())))));

            DocumentFileEncryption.decryptFile(
                    CryptoFM.getContext().getContentResolver().openInputStream(f.getUri()), getSecretKey(),
                    mKeyPass, new BufferedOutputStream(new FileOutputStream(out))

            );

        }
    }
}

From source file:org.totschnig.myexpenses.util.Utils.java

public static DocumentFile newFile(DocumentFile parentDir, String base, String mimeType, boolean addExtension) {
    int postfix = 0;
    do {/*  w w w .j  av a  2  s . com*/
        String name = base;
        if (postfix > 0) {
            name += "_" + postfix;
        }
        if (addExtension) {
            name += "." + mimeType.split("/")[1];
        }
        if (parentDir.findFile(name) == null) {
            DocumentFile result = null;
            try {
                result = parentDir.createFile(mimeType, name);
                if (result == null) {
                    AcraHelper.report(new Exception(
                            String.format("createFile returned null: mimeType %s; name %s; parent %s", mimeType,
                                    name, parentDir.getUri().toString())));
                }
            } catch (SecurityException e) {
                AcraHelper.report(new Exception(
                        String.format("createFile threw SecurityException: mimeType %s; name %s; parent %s",
                                mimeType, name, parentDir.getUri().toString())));
            }
            return result;
        }
        postfix++;
    } while (true);
}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public void openunknown(DocumentFile f, Context c, boolean forcechooser) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    String type = f.getType();/*from  w  w  w  . java2 s . com*/
    if (type != null && type.trim().length() != 0 && !type.equals("*/*")) {
        intent.setDataAndType(f.getUri(), type);
        Intent startintent;
        if (forcechooser)
            startintent = Intent.createChooser(intent, c.getResources().getString(R.string.openwith));
        else
            startintent = intent;
        try {
            c.startActivity(startintent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
            openWith(f, c);
        }
    } else {
        openWith(f, c);
    }

}

From source file:com.osama.cryptofm.tasks.MoveTask.java

private void moveDocumentFile(DocumentFile file) throws Exception {
    if (file.isDirectory()) {
        Log.d(TAG, "moveDocumentFile: Yes document file is directory");
        //change the destination folder
        mDestinationFolder = mDestinationFolder + file.getName() + "/";
        //check if destination folder is not document file
        if (FileUtils.isDocumentFile(mDestinationFolder)) {
            rootDocumentFile = rootDocumentFile.createDirectory(file.getName());
        } else {/*  ww  w.ja v  a 2 s .  c om*/
            File tmp = new File(mDestinationFolder);
            if (!tmp.exists()) {
                tmp.mkdir();
            } else {
                return;
            }
        }
        for (DocumentFile f : file.listFiles()) {
            moveDocumentFile(f);
        }
    } else {
        isNextFile = true;
        publishProgress(file.getName());
        publishProgress("" + 0);
        //check if pasting in internal storage
        if (!FileUtils.isDocumentFile(mDestinationFolder)) {
            Log.d(TAG, "moveDocumentFile: moving document file in internal storage");
            File destinationFile = new File(mDestinationFolder + file.getName());
            innerMove(CryptoFM.getContext().getContentResolver().openInputStream(file.getUri()),
                    new BufferedOutputStream(new FileOutputStream(destinationFile)), file.length());
        } else {
            Log.d(TAG, "moveDocumentFile: Moving document file honey");
            DocumentFile destFile = rootDocumentFile.createFile(file.getType(), file.getName());

            innerMove(CryptoFM.getContext().getContentResolver().openInputStream(file.getUri()),
                    CryptoFM.getContext().getContentResolver().openOutputStream(destFile.getUri()),
                    file.length());
        }
    }

    //delete the input file
    //if copying then don't
    if (SharedData.IS_COPYING_NOT_MOVING) {
        return;
    }
    if (!file.delete()) {
        throw new IOException("cannot move files");
    }
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

/**
 * Appends mp4 audio/video from {@code anotherFileDescriptor} to
 * {@code mainFileDescriptor}.//from w  w  w  .j  ava  2s.  c o  m
 */
public static DocumentFile appendNew(DocumentFile[] inputFiles) {
    try {
        DocumentFile targetFile = inputFiles[0];
        int[] inputFilesFds = new int[inputFiles.length];
        ArrayList<ParcelFileDescriptor> pfdsList = new ArrayList<ParcelFileDescriptor>();

        int i = 0;
        for (DocumentFile f : inputFiles) {
            ParcelFileDescriptor pfd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(f.getUri(), "rw");
            pfdsList.add(pfd);
            inputFilesFds[i] = pfd.getFd();
            i++;
        }

        if (targetFile.exists() && targetFile.length() > 0) {
            String tmpFileName = targetFile.getName() + ".tmp";
            DocumentFile tmpTargetFile = targetFile.getParentFile().createFile("video/mp4", tmpFileName);
            ParcelFileDescriptor targetFilePfd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(tmpTargetFile.getUri(), "rw");

            Mp4Editor.appendFds(inputFilesFds, targetFilePfd.getFd());

            targetFilePfd.close();
            for (ParcelFileDescriptor pfd : pfdsList) {
                pfd.close();
            }

            return tmpTargetFile;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public void openWith(final DocumentFile f, final Context c) {
    MaterialDialog.Builder a = new MaterialDialog.Builder(c);
    a.title(c.getResources().getString(R.string.openas));
    String[] items = new String[] { c.getResources().getString(R.string.text),
            c.getResources().getString(R.string.image), c.getResources().getString(R.string.video),
            c.getResources().getString(R.string.audio), c.getResources().getString(R.string.database),
            c.getResources().getString(R.string.other) };

    a.items(items).itemsCallback(new MaterialDialog.ListCallback() {
        @Override//from   w ww  .j av a 2  s .c o  m
        public void onSelection(MaterialDialog materialDialog, View view, int i, CharSequence charSequence) {

            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            switch (i) {
            case 0:
                intent.setDataAndType(f.getUri(), "text/*");
                break;
            case 1:
                intent.setDataAndType(f.getUri(), "image/*");
                break;
            case 2:
                intent.setDataAndType(f.getUri(), "video/*");
                break;
            case 3:
                intent.setDataAndType(f.getUri(), "audio/*");
                break;
            case 4:
                intent = new Intent(c, DbViewer.class);
                intent.putExtra("path", f.getUri());
                break;
            case 5:
                intent.setDataAndType(f.getUri(), "*/*");
                break;
            }
            try {
                c.startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show();
                openWith(f, c);
            }
        }
    });
    try {
        a.build().show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Exports a track to the sd card//from  w w  w.  j  a  v  a2  s  .  co  m
 * @param musicTrack The music track you want to export
 * @param uri The document tree
 * @return Returns whether the export was successful
 */
public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) {

    // Check for null
    if (musicTrack == null)
        return false;

    String srcFile = musicTrack.getSourceFile();

    // Could not find the source file
    if (srcFile == null)
        return false;

    String fileTmp = getTempPath() + "/tmp.mp3";

    // Copy to temp path failed
    if (!SuperUserTools.fileCopy(srcFile, fileTmp))
        return false;

    // Encrypt the file
    if (musicTrack.isEncoded()) {
        String fileTmpCrypt = getTempPath() + "/crypt.mp3";

        // Encrypts the file
        if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) {
            // Remove the old tmp file
            FileTools.fileDelete(fileTmp);

            // New tmp file
            fileTmp = fileTmpCrypt;
        } else {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "Encrypting failed! Continue with decrypted file.");
        }
    }

    String dest;
    Uri copyUri = null;
    if (uri.toString().startsWith("file://")) {
        // Build the full path
        dest = uri.buildUpon().appendPath(path).build().getPath();

        String parentDirectory = new File(dest).getParent();
        FileTools.directoryCreate(parentDirectory);
    } else {
        // Complex uri (Lollipop)
        dest = getTempPath() + "/final.mp3";

        // The root
        DocumentFile document = DocumentFile.fromTreeUri(mContext, uri);

        // Creates the subdirectories
        String[] directories = path.split("\\/");
        for (int i = 0; i < directories.length - 1; i++) {
            String directoryName = directories[i];
            boolean found = false;

            // Search all sub elements
            for (DocumentFile subDocument : document.listFiles()) {
                // Directory exists
                if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) {
                    document = subDocument;
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Create the directory
                document = document.createDirectory(directoryName);
            }
        }

        // Gets the filename
        String filename = directories[directories.length - 1];

        for (DocumentFile subDocument : document.listFiles()) {
            // Directory exists
            if (subDocument.isFile() && subDocument.getName().equals(filename)) {
                // Delete the file
                subDocument.delete();
                break;
            }
        }

        // Create the mp3 file
        document = document.createFile("music/mp3", filename);

        // Create the directories
        copyUri = document.getUri();
    }

    // We want to export the ID3 tags
    if (mID3Enable) {
        // Adds the meta data
        if (!trackWriteID3(musicTrack, fileTmp, dest)) {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "ID3 writer failed! Continue without ID3 tags.");

            // Failed, moving without meta data
            if (!FileTools.fileMove(fileTmp, dest)) {
                Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

                // Could not copy the file
                return false;
            }
        }
    } else {
        // Moving the file
        if (!FileTools.fileMove(fileTmp, dest)) {
            Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

            // Could not copy the file
            return false;
        }
    }

    // We need to copy the file to a uri
    if (copyUri != null) {
        // Lollipop only
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                // Gets the file descriptor
                ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver()
                        .openFileDescriptor(copyUri, "w");

                // Gets the output stream
                FileOutputStream fileOutputStream = new FileOutputStream(
                        parcelFileDescriptor.getFileDescriptor());

                // Gets the input stream
                FileInputStream fileInputStream = new FileInputStream(dest);

                // Copy the stream
                FileTools.fileCopy(fileInputStream, fileOutputStream);

                // Close all streams
                fileOutputStream.close();
                fileInputStream.close();
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                Logger.getInstance().logError("ExportMusicTrack", "File not found!");

                // Could not copy the file
                return false;
            } catch (IOException e) {
                Logger.getInstance().logError("ExportMusicTrack",
                        "Failed to write the document: " + e.toString());

                // Could not copy the file
                return false;
            }
        }
    }

    // Delete temp files
    cleanUp();

    // Adds the file to the media system
    //new MediaScanner(mContext, dest);

    // Done
    return true;
}