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

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

Introduction

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

Prototype

public abstract boolean isDirectory();

Source Link

Usage

From source file:com.frostwire.android.StoragePicker.java

public static String handle(Context context, int requestCode, int resultCode, Intent data) {
    String result = null;/* w  ww. java 2  s  . c om*/
    try {

        if (resultCode == Activity.RESULT_OK && requestCode == SELECT_FOLDER_REQUEST_CODE) {
            Uri treeUri = data.getData();

            ContentResolver cr = context.getContentResolver();

            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            cr.takePersistableUriPermission(treeUri, takeFlags);

            if (treeUri == null) {
                UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_null);
                result = null;
            } else {
                DocumentFile file = DocumentFile.fromTreeUri(context, treeUri);
                if (!file.isDirectory()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_not_directory);
                    result = null;
                } else if (!file.canWrite()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_cant_write);
                    result = null;
                } else {
                    LollipopFileSystem fs = (LollipopFileSystem) Platforms.fileSystem();
                    result = fs.getTreePath(treeUri);
                    if (result != null && !result.endsWith("/FrostWire")) {
                        DocumentFile f = file.findFile("FrostWire");
                        if (f == null) {
                            file.createDirectory("FrostWire");
                        }
                    }
                }
            }
        }
    } catch (Throwable e) {
        UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_error);
        LOG.error("Error handling folder selection", e);
        result = null;
    }

    if (result != null) {
        ConfigurationManager.instance().setStoragePath(result);
        BTEngine.ctx.dataDir = Platforms.data();
        BTEngine.ctx.torrentsDir = Platforms.torrents();
    }

    return result;
}

From source file:org.dkf.jmule.StoragePicker.java

public static String handle(Context context, int requestCode, int resultCode, Intent data) {
    String result = null;/*from   www  .j a  va  2 s.co  m*/
    try {

        if (resultCode == Activity.RESULT_OK && requestCode == SELECT_FOLDER_REQUEST_CODE) {
            Uri treeUri = data.getData();

            ContentResolver cr = context.getContentResolver();

            Method takePersistableUriPermissionM = cr.getClass().getMethod("takePersistableUriPermission",
                    Uri.class, int.class);
            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePersistableUriPermissionM.invoke(cr, treeUri, takeFlags);

            if (treeUri == null) {
                UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_null);
                result = null;
            } else {
                DocumentFile file = DocumentFile.fromTreeUri(context, treeUri);
                if (!file.isDirectory()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_not_directory);
                    result = null;
                } else if (!file.canWrite()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_cant_write);
                    result = null;
                } else {
                    if (Platforms.get().saf()) {
                        LollipopFileSystem fs = (LollipopFileSystem) Platforms.fileSystem();
                        result = fs.getTreePath(treeUri);

                        // TODO - remove below code - only for testing SD card writing
                        File testFile = new File(result, "test_file.txt");
                        LOG.info("test file {}", testFile);

                        try {
                            Pair<ParcelFileDescriptor, DocumentFile> fd = fs.openFD(testFile, "rw");
                            if (fd != null && fd.first != null && fd.second != null) {
                                AndroidFileHandler ah = new AndroidFileHandler(testFile, fd.second, fd.first);
                                ByteBuffer bb = ByteBuffer.allocate(48);
                                bb.putInt(1).putInt(2).putInt(3).putInt(44).putInt(22);
                                bb.flip();
                                ah.getWriteChannel().write(bb);
                                ah.close();
                            } else {
                                LOG.error("unable to create file {}", testFile);
                            }
                        } catch (Exception e) {
                            LOG.error("unable to fill file {} error {}", testFile, e);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_error);
        LOG.error("Error handling folder selection {}", e);
        result = null;
    }

    return result;
}

From source file:com.frostwire.android.gui.StoragePicker.java

public static String handle(Context context, int requestCode, int resultCode, Intent data) {
    String result = null;//from  w  w w . ja  v a  2s .  com
    try {

        if (resultCode == Activity.RESULT_OK && requestCode == SELECT_FOLDER_REQUEST_CODE) {
            Uri treeUri = data.getData();

            ContentResolver cr = context.getContentResolver();

            Method takePersistableUriPermissionM = cr.getClass().getMethod("takePersistableUriPermission",
                    Uri.class, int.class);
            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePersistableUriPermissionM.invoke(cr, treeUri, takeFlags);

            if (treeUri == null) {
                UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_null);
                result = null;
            } else {
                DocumentFile file = DocumentFile.fromTreeUri(context, treeUri);
                if (!file.isDirectory()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_not_directory);
                    result = null;
                } else if (!file.canWrite()) {
                    UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_cant_write);
                    result = null;
                } else {
                    result = getFullPathFromTreeUri(context, treeUri);
                }
            }
        }
    } catch (Throwable e) {
        UIUtils.showShortMessage(context, R.string.storage_picker_treeuri_error);
        LOG.error("Error handling folder selection", e);
        result = null;
    }

    return result;
}

From source file:com.amaze.filemanager.filesystem.RootHelper.java

public static HybridFileParcelable generateBaseFile(DocumentFile file, boolean showHidden) {
    long size = 0;
    if (!file.isDirectory())
        size = file.length();//from  w ww .j a v a  2  s .c o m
    HybridFileParcelable baseFile = new HybridFileParcelable(file.getName(), parseDocumentFilePermission(file),
            file.lastModified(), size, file.isDirectory());
    baseFile.setName(file.getName());
    baseFile.setMode(OpenMode.OTG);

    return baseFile;
}

From source file:com.amaze.carbonfilemanager.filesystem.RootHelper.java

public static BaseFile generateBaseFile(DocumentFile file, boolean showHidden) {
    long size = 0;
    if (!file.isDirectory())
        size = file.length();/*from  w  w  w . ja  va  2 s .  c o m*/
    BaseFile baseFile = new BaseFile(file.getName(), parseDocumentFilePermission(file), file.lastModified(),
            size, file.isDirectory());
    baseFile.setName(file.getName());
    baseFile.setMode(OpenMode.OTG);

    return baseFile;
}

From source file:com.github.chenxiaolong.dualbootpatcher.switcher.InAppFlashingFragment.java

@Nullable
private static String[] getDirectories(Context context, Uri uri) {
    final ArrayList<String> filenames = new ArrayList<>();
    DocumentFile directory = FileUtils.getDocumentFile(context, uri);
    DocumentFile[] files = directory.listFiles();

    if (files == null) {
        return null;
    }// www . j a  va 2  s .co m

    for (DocumentFile file : files) {
        if (file.isDirectory()) {
            filenames.add(file.getName());
        }
    }

    Collections.sort(filenames);

    return filenames.toArray(new String[filenames.size()]);
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static DocumentFile getDirectory(Context context, File dir, boolean create) {
    try {//from w w w . j a  va 2  s .  c  o m
        String path = dir.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null && cached.isDirectory()) {
            return cached;
        }

        String baseFolder = getExtSdCardFolder(context, dir);
        if (baseFolder == null) {
            if (create) {
                return dir.mkdirs() ? DocumentFile.fromFile(dir) : null;
            } else {
                return dir.isDirectory() ? DocumentFile.fromFile(dir) : null;
            }
        }

        baseFolder = combineRoot(baseFolder);

        String fullPath = dir.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);

        // special FrostWire case
        if (create) {
            if (baseFolder.endsWith("/FrostWire") && !f.exists()) {
                baseFolder = baseFolder.substring(0, baseFolder.length() - 10);
                rootUri = getDocumentUri(context, new File(baseFolder));
                f = DocumentFile.fromTreeUri(context, rootUri);
                f = f.findFile("FrostWire");
                if (f == null) {
                    f = f.createDirectory("FrostWire");
                    if (f == null) {
                        return null;
                    }
                }
            }
        }
        for (String segment : segments) {
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                if (create) {
                    f = f.createDirectory(segment);
                    if (f == null) {
                        return null;
                    }
                } else {
                    return null;
                }
            }
        }

        f = f.isDirectory() ? f : null;

        if (f != null) {
            CACHE.put(path, f);
        }

        return f;
    } catch (Throwable e) {
        LOG.error("Error getting directory: " + dir, e);
        return null;
    }
}

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);
    }// www .j  av a  2s. co  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.DeleteTask.java

private void deleteDocFile(DocumentFile docFile) throws IOException {
    Log.d(TAG, "deleteDocFile: Deleting document file");
    publishProgress(docFile.getName());//from  w  w w.  j a  va  2  s. c om
    if (docFile.isDirectory() && docFile.listFiles().length > 0) {
        for (DocumentFile d : docFile.listFiles()) {
            deleteDocFile(d);
        }
    }
    if (!docFile.delete()) {
        throw new IOException("cannot delete files");
    }
}

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:
 * {/*w w w  .  j ava2  s. c om*/
 *     "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;
    }
}