首页 > 解决方案 > 将特定文件夹中的 Pdf 文件显示为片段

问题描述

我正在尝试为 API 级别 21 及更高级别构建 Pdf Scanner Android 应用程序,在应用程序中,我可以选择显示和管理应用程序通过应用程序创建的所有 pdf 文件。我想从 Documents/PDFScanner 文件夹中获取 Pdf 文件并在片段中显示它们。到目前为止,我得到的是空数组,但文件夹中有 Pdf 文件。我已经在 Android 11 和 Android 8.1 设备上测试了代码。这是我获取pdf文件的功能

private void getPDFFilesFromDirecotry() {
    Uri collection = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
    } else {
        collection = MediaStore.Files.getContentUri("external");
    }

    String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};

    Cursor mediaCursor = applicationContext.getContentResolver().query(collection,
            projection,
            MediaStore.MediaColumns.DATA + " LIKE?",
            new String[]{Environment.DIRECTORY_DOCUMENTS + "/PDFScanner"},
            null);

    Log.e("TAG", "Message: " + mediaCursor.getCount());
    if (mediaCursor == null || mediaCursor.getCount() <= 0 || !mediaCursor.moveToFirst()) {
        Log.e("tag","No data");
        return;
    }
    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
    MediaScannerConnection.scanFile(applicationContext, new String[]{file.getPath()}, new String[]{mimetype}, null);

    while (mediaCursor.moveToNext()) {
        Log.e("TAG", "Message: ");
        String path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME));
        Log.e("TAG", "getPDFFilesFromDirectory Path: " + path);
        if (path != null) {
            ivNoData.setVisibility(View.GONE);
            file = new File(path);

            String name = file.getName();
            int position = name.lastIndexOf(".");
            if (position > 0 && position < name.length() - 1) {
                name = name.substring(0, position);
            }
            Date dateinMillis = new Date(file.lastModified());
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm a");
            String date = dateFormat.format(dateinMillis);
            String size = formatSize(file.length());

            viewFilesArray.add(new ViewFilesModel(path, name, size, date));
        }
    }
    mediaCursor.close();

    Log.e("TAG", "getPDFFilesFromDirectory: " + viewFilesArray.size());
    filesAdapter.notifyDataSetChanged();
}

谢谢您的帮助。

标签: javaandroidpdfmediastoreandroid-external-storage

解决方案


推荐阅读