java - 将特定文件夹中的 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();
}
谢谢您的帮助。
解决方案
推荐阅读
- c++ - 如何正确地将字符数组写入文本文件
- wordpress - WooCommerce 产品库存重置为 0
- c++ - 修复 C++ VSCode 中的错误“未定义对“Class::Function”的引用
- tensorflow - 使用 conv2d 等的 python 函数复制 TFLite 模型层
- c# - 如何在 ac# 函数中设置超时?
- html - JQuery如何获取这个div的数量
- ckeditor - 如何在ckeditor5中显示/文本工具栏按钮
- regex - 如何用正则表达式对字符和数字求和?
- python - += 在这种情况下是什么意思?
- flutter - 如何在颤振中使用扩展