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.osama.cryptofm.filemanager.listview.FileSelectionManagement.java

void openFile(final String filename) {
    if (SharedData.IS_IN_COPY_MODE) {
        return;/*from  w w  w .  ja v  a2s .co m*/
    }
    if (FileUtils.getExtension(filename).equals("pgp")) {
        Log.d(TAG, "openFile: File name is: " + filename);
        if (SharedData.KEY_PASSWORD == null) {
            final Dialog dialog = new Dialog(mContext);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.password_dialog_layout);
            dialog.show();
            dialog.findViewById(R.id.cancel_decrypt_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            final EditText editText = (EditText) dialog.findViewById(R.id.key_password);
            dialog.findViewById(R.id.decrypt_file_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (editText.getText().length() < 1) {
                        editText.setError("please give me your encryption password");
                        return;
                    } else {
                        SharedData.KEY_PASSWORD = editText.getText().toString();
                        dialog.dismiss();
                        new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD,
                                SharedData.USERNAME, FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD)
                                        .execute();
                    }

                }
            });
        } else {
            new DecryptTask(mContext, mFileListAdapter, SharedData.DB_PASSWWORD, SharedData.USERNAME,
                    FileUtils.CURRENT_PATH + filename, SharedData.KEY_PASSWORD).execute();
        }

    } else {
        //open file
        if (SharedData.EXTERNAL_SDCARD_ROOT_PATH != null
                && FileUtils.CURRENT_PATH.contains(SharedData.EXTERNAL_SDCARD_ROOT_PATH)) {
            //open the document file
            DocumentFile file = FileDocumentUtils.getDocumentFile(FileUtils.getFile(filename));
            Intent intent = new Intent();
            intent.setDataAndType(file.getUri(), file.getType());
            intent.setAction(Intent.ACTION_VIEW);
            Intent x = Intent.createChooser(intent, "Open with");
            mContext.startActivity(x);
            return;
        }
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getExtension(filename));

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            Uri uri = FileProvider.getUriForFile(mContext,
                    mContext.getApplicationContext().getPackageName() + ".provider",
                    FileUtils.getFile(filename));
            intent.setDataAndType(uri, mimeType);
        } else {
            intent.setDataAndType(Uri.fromFile(FileUtils.getFile(filename)), mimeType);
        }
        intent.setAction(Intent.ACTION_VIEW);
        Intent x = Intent.createChooser(intent, "Open with: ");
        mContext.startActivity(x);
    }
}

From source file:io.v.android.apps.syncslides.DeckChooserFragment.java

private byte[] readImage(DocumentFile dir, String fileName) throws IOException {
    DocumentFile file = dir.findFile(fileName);
    if (file == null) {
        throw new FileNotFoundException("Image file doesn't exist: " + fileName);
    }/*from w ww  .j av  a2 s . c om*/
    return ByteStreams.toByteArray(getActivity().getContentResolver().openInputStream(file.getUri()));
}

From source file:io.v.syncslides.lib.DeckImporter.java

private Void importDeckImpl(DocumentFile dir) throws ImportException {
    if (!dir.isDirectory()) {
        throw new ImportException("Must import from a directory, got: " + dir);
    }/*from w ww .java  2  s  .  c  o m*/
    // Read the deck metadata file.
    DocumentFile metadataFile = dir.findFile(DECK_JSON);
    if (metadataFile == null) {
        throw new ImportException("Couldn't find deck metadata file 'deck.json'");
    }
    JSONObject metadata = null;
    try {
        String data = new String(
                ByteStreams.toByteArray(mContentResolver.openInputStream(metadataFile.getUri())),
                Charsets.UTF_8);
        metadata = new JSONObject(data);
    } catch (FileNotFoundException e) {
        throw new ImportException("Couldn't open deck metadata file", e);
    } catch (IOException e) {
        throw new ImportException("Couldn't read data from deck metadata file", e);
    } catch (JSONException e) {
        throw new ImportException("Couldn't parse deck metadata", e);
    }

    try {
        String id = UUID.randomUUID().toString();
        String title = metadata.getString(TITLE);
        byte[] thumbData = readImage(dir, metadata.getString(THUMB));
        Deck deck = new DeckImpl(title, thumbData, id);
        Slide[] slides = readSlides(dir, metadata);
        sync(mDB.importDeck(deck, slides));
    } catch (JSONException e) {
        throw new ImportException("Invalid format for deck metadata", e);
    } catch (IOException e) {
        throw new ImportException("Error interpreting deck metadata", e);
    } catch (VException e) {
        throw new ImportException("Error importing deck", e);
    }
    return null;
}

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

private void move(File f) throws Exception {
    if (f.isDirectory()) {
        //check if destination folder is in external sdcard
        if (FileUtils.isDocumentFile(mDestinationFolder)) {
            DocumentFile rootDocumentFile = FileDocumentUtils.getDocumentFile(new File(mDestinationFolder));
            rootDocumentFile.createDirectory(f.getName());
        } else {// ww  w  .  ja v  a2 s.co m
            //create folder in the destination
            mDestinationFolder = mDestinationFolder + f.getName() + "/";

            File tmp = new File(mDestinationFolder);
            if (!tmp.exists()) {
                tmp.mkdir();
            } else {
                return;
            }

        }
        Log.d(TAG, "move: File is a directory");
        for (File file : f.listFiles()) {
            move(file);
        }
    } else {
        Log.d(TAG, "move: Moving file: " + f.getName());
        Log.d(TAG, "move: Destination folder is: " + mDestinationFolder);
        isNextFile = true;
        publishProgress(f.getName());
        publishProgress("" + 0);
        if (FileUtils.isDocumentFile(mDestinationFolder)) {
            DocumentFile dest = rootDocumentFile.createFile(FileUtils.getExtension(f.getName()), f.getName());
            innerMove(new BufferedInputStream(new FileInputStream(f)),
                    CryptoFM.getContext().getContentResolver().openOutputStream(dest.getUri()), f.length());
        } else {
            //check if file already exits
            File destinationFile = new File(mDestinationFolder + f.getName());
            if (destinationFile.exists()) {
                return;
            }

            innerMove(new BufferedInputStream(new FileInputStream(f)),
                    new BufferedOutputStream(new FileOutputStream(destinationFile)), f.length());
        }
    }

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

From source file:com.github.chenxiaolong.dualbootpatcher.switcher.service.MbtoolTask.java

private String getPathFromUri(@NonNull Uri uri, @NonNull MbtoolInterface iface)
        throws IOException, MbtoolException {
    // Get URI from DocumentFile, which will handle the translation of tree URIs to document
    // URIs, which continuing to work with file:// URIs
    DocumentFile df = FileUtils.getDocumentFile(getContext(), uri);
    uri = df.getUri();

    ParcelFileDescriptor pfd = null;/*from   w  ww.  j a v  a  2  s  .c o m*/
    try {
        pfd = getContext().getContentResolver().openFileDescriptor(uri, "r");
        if (pfd == null) {
            printBoldText(Color.RED, "Failed to open: " + uri);
            return null;
        }

        String fdSource = "/proc/" + LibC.CWrapper.getpid() + "/fd/" + pfd.getFd();
        try {
            return iface.pathReadlink(fdSource);
        } catch (MbtoolCommandException e) {
            printBoldText(Color.RED, "Failed to resolve symlink: " + fdSource + ": " + e.getMessage() + "\n");
            return null;
        }
    } finally {
        IOUtils.closeQuietly(pfd);
    }
}

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

private void setRecorderFilePath() {
    if (!appSettingsManager.GetWriteExternal()) {
        mediaRecorder.setOutputFile(recordingFile.getAbsolutePath());
    } else {//from w  w  w.j  a va 2 s .  c  o  m
        Uri uri = Uri.parse(appSettingsManager.GetBaseFolder());
        DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("*/*", recordingFile.getName());
        ParcelFileDescriptor fileDescriptor = null;
        try {
            fileDescriptor = cameraUiWrapper.getContext().getContentResolver().openFileDescriptor(wr.getUri(),
                    "rw");
            mediaRecorder.setOutputFile(fileDescriptor.getFileDescriptor());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            try {
                fileDescriptor.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

From source file:de.k3b.android.toGoZip.ZipStorageDocumentFile.java

/**
 *  {@inheritDoc}/*from www . j ava 2 s.c  o  m*/
 */
@Override
public OutputStream createOutputStream(ZipInstance zipInstance) throws FileNotFoundException {
    // find existing
    DocumentFile zipFile = getDocumentFile(zipInstance);

    // if not found create it.
    if (zipFile == null) {
        final String mimetype = (zipInstance == ZipInstance.logfile) ? MIMETYPE_TEXT : MIMETYPE_ZIP;
        zipFile = directory.createFile(mimetype, getZipFileNameWithoutPath(zipInstance));
    }

    if (zipFile != null)
        return context.getContentResolver().openOutputStream(zipFile.getUri(), "w");

    return null;
}

From source file:freed.viewer.dngconvert.DngConvertingFragment.java

private void convertRawToDng(File file) {
    byte[] data = null;
    try {/*from   www .  j  a  v  a  2s .c om*/
        data = RawToDng.readFile(file);
        Log.d("Main", "Filesize: " + data.length + " File:" + file.getAbsolutePath());

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String out = null;
    if (file.getName().endsWith(FileEnding.RAW))
        out = file.getAbsolutePath().replace(FileEnding.RAW, FileEnding.DNG);
    if (file.getName().endsWith(FileEnding.BAYER))
        out = file.getAbsolutePath().replace(FileEnding.BAYER, FileEnding.DNG);
    RawToDng dng = RawToDng.GetInstance();
    String intsd = StringUtils.GetInternalSDCARD();
    if (VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP || file.getAbsolutePath().contains(intsd))
        dng.setBayerData(data, out);
    else {
        DocumentFile df = ((ActivityInterface) getActivity()).getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("image/dng", file.getName().replace(FileEnding.JPG, FileEnding.DNG));
        ParcelFileDescriptor pfd = null;
        try {

            pfd = getContext().getContentResolver().openFileDescriptor(wr.getUri(), "rw");
        } catch (FileNotFoundException | IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        if (pfd != null) {
            dng.SetBayerDataFD(data, pfd, file.getName());
            try {
                pfd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pfd = null;
        }
    }
    dng.setExifData(100, 0, 0, 0, 0, "", "0", 0);
    if (fakeGPS.isChecked())
        dng.SetGpsData(Altitude, Latitude, Longitude, Provider, gpsTime);
    dng.WriteDngWithProfile(dngprofile);
    data = null;
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    getActivity().sendBroadcast(intent);
    if (filesToConvert.length == 1) {

        final Bitmap map = new RawUtils().UnPackRAW(out);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageView.setImageBitmap(map);
            }
        });
    }
}

From source file:io.v.android.apps.syncslides.DeckChooserFragment.java

/**
 * Import a slide deck from the given (local) folder.
 *
 * The folder must contain a JSON metadata file 'deck.json' with the following format:
 * {//  ww w. ja va  2s  .com
 *     "Title" : "<title>",
 *     "Thumb" : "<filename>,
 *     "Slides" : [
 *          {
 *              "Thumb" : "<thumb_filename1>",
 *              "Image" : "<image_filename1>",
 *              "Note" : "<note1>"
 *          },
 *          {
 *              "Thumb" : "<thumb_filename2>",
 *              "Image" : "<image_filename2>",
 *              "Note" : "<note2>"
 *          },
 *
 *          ...
 *     ]
 * }
 *
 * All the filenames must be local to the given folder.
 */
private void importDeck(DocumentFile dir) {
    if (!dir.isDirectory()) {
        toast("Must import from a directory, got: " + dir);
        return;
    }
    // Read the deck metadata file.
    DocumentFile metadataFile = dir.findFile("deck.json");
    if (metadataFile == null) {
        toast("Couldn't find deck metadata file 'deck.json'");
        return;
    }
    JSONObject metadata = null;
    try {
        String data = new String(
                ByteStreams
                        .toByteArray(getActivity().getContentResolver().openInputStream(metadataFile.getUri())),
                Charsets.UTF_8);
        metadata = new JSONObject(data);
    } catch (FileNotFoundException e) {
        toast("Couldn't open deck metadata file: " + e.getMessage());
        return;
    } catch (IOException e) {
        toast("Couldn't read data from deck metadata file: " + e.getMessage());
        return;
    } catch (JSONException e) {
        toast("Couldn't parse deck metadata: " + e.getMessage());
        return;
    }

    try {
        String id = UUID.randomUUID().toString();
        String title = metadata.getString("Title");
        byte[] thumbData = readImage(dir, metadata.getString("Thumb"));
        Deck deck = DeckFactory.Singleton.get().make(title, thumbData, id);
        Slide[] slides = readSlides(dir, metadata);
        DB.Singleton.get(getActivity().getApplicationContext()).importDeck(deck, slides, null);
    } catch (JSONException e) {
        toast("Invalid format for deck metadata: " + e.getMessage());
        return;
    } catch (IOException e) {
        toast("Error interpreting deck metadata: " + e.getMessage());
        return;
    }
}

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

public static Result checkAppDir() {
    if (!Utils.isExternalStorageAvailable()) {
        return new Result(false, R.string.external_storage_unavailable);
    }/*from   w w  w  .ja va2 s .co m*/
    DocumentFile appDir = getAppDir();
    if (appDir == null) {
        return new Result(false, R.string.io_error_appdir_null);
    }
    return dirExistsAndIsWritable(appDir) ? new Result(true)
            : new Result(false, R.string.app_dir_not_accessible,
                    FileUtils.getPath(MyApplication.getInstance(), appDir.getUri()));
}