Java Code Examples for androidx.documentfile.provider.DocumentFile#getName()

The following examples show how to use androidx.documentfile.provider.DocumentFile#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocalBackupStorage.java    From SAI with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<Uri> listBackupFiles() {
    List<Uri> uris = new ArrayList<>();

    DocumentFile backupsDir = SafUtils.docFileFromTreeUriOrFileUri(mContext, getBackupDirUriOrThrow());
    if (backupsDir == null)
        return uris;

    for (DocumentFile docFile : backupsDir.listFiles()) {
        if (docFile.isDirectory())
            continue;

        String docName = docFile.getName();
        if (docName == null)
            continue;

        String docExt = Utils.getExtension(docName);
        if (docExt == null || !docExt.toLowerCase().equals("apks"))
            continue;

        uris.add(namespaceUri(docFile.getUri()));
    }

    return uris;
}
 
Example 2
Source File: LibImportDialogFragment.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
private Map<Site, DocumentFile> getSiteFolders() {
    Helper.assertNonUiThread();
    Map<Site, DocumentFile> result = new EnumMap<>(Site.class);

    if (!Preferences.getStorageUri().isEmpty()) {
        Uri rootUri = Uri.parse(Preferences.getStorageUri());
        DocumentFile rootFolder = DocumentFile.fromTreeUri(requireContext(), rootUri);
        if (rootFolder != null && rootFolder.exists()) {
            List<DocumentFile> subfolders = FileHelper.listFolders(requireContext(), rootFolder);
            String folderName;
            for (DocumentFile f : subfolders)
                if (f.getName() != null) {
                    folderName = f.getName().toLowerCase();
                    for (Site s : Site.values()) {
                        if (folderName.equalsIgnoreCase(s.getFolder())) {
                            result.put(s, f);
                            break;
                        }
                    }
                }
        }
    }
    return result;
}
 
Example 3
Source File: ImportHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
@Nullable
private static DocumentFile addHentoidFolder(@NonNull final Context context, @NonNull final DocumentFile baseFolder) {
    String folderName = baseFolder.getName();
    if (null == folderName) folderName = "";

    // Don't create a .Hentoid subfolder inside the .Hentoid (or Hentoid) folder the user just selected...
    if (!isHentoidFolderName(folderName)) {
        DocumentFile targetFolder = getExistingHentoidDirFrom(context, baseFolder);

        // If not, create one
        if (targetFolder.getUri().equals(baseFolder.getUri()))
            return targetFolder.createDirectory(Consts.DEFAULT_LOCAL_DIRECTORY);
        else return targetFolder;
    }
    return baseFolder;
}
 
Example 4
Source File: ZipUtil.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
private static void addFile(@NonNull final Context context,
                            @NonNull final DocumentFile file,
                            final ZipOutputStream stream,
                            final byte[] data) throws IOException {
    Timber.d("Adding: %s", file);
    try (InputStream fi = FileHelper.getInputStream(context, file); BufferedInputStream origin = new BufferedInputStream(fi, BUFFER)) {

        ZipEntry zipEntry = new ZipEntry(file.getName());
        stream.putNextEntry(zipEntry);
        int count;

        while ((count = origin.read(data, 0, BUFFER)) != -1) {
            stream.write(data, 0, count);
        }
    }
}
 
Example 5
Source File: BaseUriFtpFile.java    From ProjectX with Apache License 2.0 6 votes vote down vote up
@Override
public List<? extends FtpFile> listFiles() {
    if (!mDocument.exists() || !mDocument.isDirectory())
        return null;
    final DocumentFile[] children = mDocument.listFiles();
    if (children.length <= 0)
        return new ArrayList<>(0);
    final ArrayList<BaseUriFtpFile> files = new ArrayList<>(children.length);
    for (DocumentFile child : children) {
        final String absolutePath = mAbsolutePath + "/" + child.getName();
        final BaseUriFtpFile item = onCreateChild();
        item.set(mContentResolver, child, absolutePath);
        files.add(item);
    }
    return files;
}
 
Example 6
Source File: SafUtils.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public static String getFileNameFromContentUri(Context context, Uri contentUri) {
    DocumentFile documentFile = docFileFromSingleUriOrFileUri(context, contentUri);

    if (documentFile == null)
        return null;

    return documentFile.getName();
}
 
Example 7
Source File: LibImportDialogFragment.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
private void mapToContent(@NonNull Content c, @NonNull DocumentFile siteFolder) {
    List<DocumentFile> bookfolders;
    if (bookFoldersCache.containsKey(c.getSite()))
        bookfolders = bookFoldersCache.get(c.getSite());
    else {
        bookfolders = FileHelper.listFolders(requireContext(), siteFolder);
        bookFoldersCache.put(c.getSite(), bookfolders);
    }
    boolean filesFound = false;
    if (bookfolders != null) {
        // Look for the book ID
        c.populateUniqueSiteId();
        for (DocumentFile f : bookfolders)
            if (f.getName() != null && f.getName().contains(ContentHelper.formatBookId(c))) {
                // Cache folder Uri
                c.setStorageUri(f.getUri().toString());
                // Cache JSON Uri
                DocumentFile json = FileHelper.findFile(requireContext(), f, Consts.JSON_FILE_NAME_V2);
                if (json != null) c.setJsonUri(json.getUri().toString());
                // Create the images from detected files
                c.setImageFiles(ContentHelper.createImageListFromFolder(requireContext(), f));
                filesFound = true;
                break;
            }
    }
    // If no local storage found for the book, it goes in the errors queue (except if it already was in progress)
    if (!filesFound) {
        if (!c.getStatus().equals(StatusContent.DOWNLOADING) && !c.getStatus().equals(StatusContent.PAUSED))
            c.setStatus(StatusContent.ERROR);
        List<ErrorRecord> errors = new ArrayList<>();
        errors.add(new ErrorRecord(ErrorType.IMPORT, "", "Book", "No local images found when importing - Please redownload", Instant.now()));
        c.setErrorLog(errors);
    }
}
 
Example 8
Source File: ImportHelper.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
public static DocumentFile getExistingHentoidDirFrom(@NonNull final Context context, @NonNull final DocumentFile root) {
    if (!root.exists() || !root.isDirectory() || null == root.getName()) return root;

    // Selected folder _is_ the Hentoid folder
    if (isHentoidFolderName(root.getName())) return root;

    // If not, look for it in its children
    List<DocumentFile> hentoidDirs = FileHelper.listFoldersFilter(context, root, hentoidFolderNames);
    if (!hentoidDirs.isEmpty()) return hentoidDirs.get(0);
    else return root;
}
 
Example 9
Source File: RecordingService.java    From libcommon with Apache License 2.0 4 votes vote down vote up
/**
	 * #startの実態, mSyncをロックして呼ばれる
	 * @param outputDir 出力ディレクトリ
	 * @param name 出力ファイル名(拡張子なし)
	 * @param videoFormat
	 * @param audioFormat
	 * @throws IOException
	 */
	@SuppressLint("NewApi")
	protected void internalStart(
		@NonNull final DocumentFile outputDir,
		@NonNull final String name,
		@Nullable final MediaFormat videoFormat,
		@Nullable final MediaFormat audioFormat) throws IOException {

		if (DEBUG) Log.v(TAG, "internalStart:");
		final DocumentFile output = outputDir.createFile("*/*", name + ".mp4");
		IMuxer muxer = null;
		if (BuildCheck.isOreo()) {
			if (USE_MEDIASTORE_OUTPUT_STREAM) {
				if (DEBUG) Log.v(TAG, "internalStart:create MediaMuxerWrapper using MediaStoreOutputStream");
				muxer = new MediaMuxerWrapper(
//					new MediaStoreOutputStream(this, "*/mp4", null, output.getName(), UriHelper.getPath(this, output.getUri())),
					new MediaStoreOutputStream(this, "video/mp4", Environment.DIRECTORY_MOVIES + "/" + Const.APP_DIR, output.getName()),
					MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
			} else {
				if (DEBUG) Log.v(TAG, "internalStart:create MediaMuxerWrapper using ContentResolver");
				muxer = new MediaMuxerWrapper(getContentResolver()
					.openFileDescriptor(output.getUri(), "rw").getFileDescriptor(),
					MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
			}
		} else {
			if (DEBUG) Log.v(TAG, "internalStart:create MediaMuxerWrapper using File");
			final String path = UriHelper.getPath(this, output.getUri());
			final File f = new File(UriHelper.getPath(this, output.getUri()));
			if (/*!f.exists() &&*/ f.canWrite()) {
				// 書き込めるファイルパスを取得できればそれを使う
				muxer = new MediaMuxerWrapper(path,
					MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
			} else {
				Log.w(TAG, "cant't write to the file, try to use VideoMuxer instead");
			}
		}
		if (muxer == null) {
			throw new IllegalArgumentException();
		}
		mMuxer = muxer;
		mVideoTrackIx = videoFormat != null ? muxer.addTrack(videoFormat) : -1;
		mAudioTrackIx = audioFormat != null ? muxer.addTrack(audioFormat) : -1;
		mMuxer.start();
		synchronized (mSync) {
			mSync.notifyAll();
		}
	}
 
Example 10
Source File: AttachmentHandler.java    From tindroid with Apache License 2.0 4 votes vote down vote up
@NonNull
static FileDetails getFileDetails(@NonNull final Context context, @NonNull Uri uri, @Nullable String filePath) {
    final ContentResolver resolver = context.getContentResolver();
    String fname = null;
    long fsize = 0L;
    int orientation = -1;

    FileDetails result = new FileDetails();

    String mimeType = resolver.getType(uri);
    if (mimeType == null) {
        mimeType = UiUtils.getMimeType(uri);
    }
    result.mimeType = mimeType;

    String[] projection;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        projection = new String[]{OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE, MediaStore.MediaColumns.ORIENTATION};
    } else {
        projection = new String[]{OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};
    }
    try (Cursor cursor = resolver.query(uri, projection, null, null, null)) {
        if (cursor != null && cursor.moveToFirst()) {
            fname = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            fsize = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                int idx = cursor.getColumnIndex(MediaStore.MediaColumns.ORIENTATION);
                if (idx >= 0) {
                    orientation = cursor.getInt(idx);
                }
            }
        }
    }
    // In degrees.
    result.imageOrientation = orientation;

    // Still no size? Try opening directly.
    if (fsize <= 0 || orientation < 0) {
        String path = filePath != null ? filePath : UiUtils.getContentPath(context, uri);
        if (path != null) {
            result.filePath = path;

            File file = new File(path);
            if (fname == null) {
                fname = file.getName();
            }
            fsize = file.length();
        } else {
            try {
                DocumentFile df = DocumentFile.fromSingleUri(context, uri);
                if (df != null) {
                    fname = df.getName();
                    fsize = df.length();
                }
            } catch (SecurityException ignored) {}
        }
    }

    result.fileName = fname;
    result.fileSize = fsize;

    return result;
}
 
Example 11
Source File: Api29MigrationActivity.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
public void onSelectSAFRootFolder(@NonNull final Uri treeUri) {

        boolean isUriPermissionPeristed = false;
        ContentResolver contentResolver = getContentResolver();
        String treeUriId = DocumentsContract.getTreeDocumentId(treeUri);

        for (UriPermission p : contentResolver.getPersistedUriPermissions()) {
            if (DocumentsContract.getTreeDocumentId(p.getUri()).equals(treeUriId)) {
                isUriPermissionPeristed = true;
                Timber.d("Uri permission already persisted for %s", treeUri);
                break;
            }
        }

        if (!isUriPermissionPeristed) {
            Timber.d("Persisting Uri permission for %s", treeUri);
            // Release previous access permissions, if different than the new one
            FileHelper.revokePreviousPermissions(contentResolver, treeUri);
            // Persist new access permission
            contentResolver.takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        DocumentFile selectedFolder = DocumentFile.fromTreeUri(this, treeUri);
        if (selectedFolder != null) {
            String folderName = selectedFolder.getName();
            if (null == folderName) folderName = "";

            // Make sure we detect the Hentoid folder if it's a child of the selected folder
            if (!ImportHelper.isHentoidFolderName(folderName))
                selectedFolder = ImportHelper.getExistingHentoidDirFrom(this, selectedFolder);
        }

        // If no existing hentoid folder is detected, tell the user to select it again
        if (null == selectedFolder || null == selectedFolder.getName() || !ImportHelper.isHentoidFolderName(selectedFolder.getName()))
        {
            ToastUtil.toast("Please select an existing Hentoid folder. Its location is displayed on screen.");
            return;
        }
        scanLibrary(selectedFolder);
    }
 
Example 12
Source File: FileInfoDialog.java    From turbo-editor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    View view = new DialogHelper.Builder(getActivity())
            .setTitle(R.string.info)
            .setView(R.layout.dialog_fragment_file_info)
            .createSkeletonView();
    //final View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_fragment_file_info, null);

    ListView list = (ListView) view.findViewById(android.R.id.list);

    DocumentFile file = DocumentFile.fromFile(new File(AccessStorageApi.getPath(getActivity(), (Uri) getArguments().getParcelable("uri"))));

    if (file == null && Device.hasKitKatApi()) {
        file = DocumentFile.fromSingleUri(getActivity(), (Uri) getArguments().getParcelable("uri"));
    }

    // Get the last modification information.
    Long lastModified = file.lastModified();

    // Create a new date object and pass last modified information
    // to the date object.
    Date date = new Date(lastModified);

    String[] lines1 = {
            getString(R.string.name),
            //getString(R.string.folder),
            getString(R.string.size),
            getString(R.string.modification_date)
    };
    String[] lines2 = {
            file.getName(),
            //file.getParent(),
            FileUtils.byteCountToDisplaySize(file.length()),
            date.toString()
    };

    list.setAdapter(new AdapterTwoItem(getActivity(), lines1, lines2));


    return new AlertDialog.Builder(getActivity())
            .setView(view)
            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }
            )
            .create();
}
 
Example 13
Source File: FileHelper.java    From Hentoid with Apache License 2.0 2 votes vote down vote up
/**
 * Open the given file using the device's app(s) of choice
 *
 * @param context Context
 * @param aFile   File to be opened
 */
public static void openFile(@NonNull Context context, @NonNull DocumentFile aFile) {
    String fileName = (null == aFile.getName()) ? "" : aFile.getName();
    tryOpenFile(context, aFile.getUri(), fileName, aFile.isDirectory());
}