kotlin 从特定文件夹中阅读文件,并在recyclerview android中显示它们

a14dhokn  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(148)

我已经从外部存储中提取了所有PDF文件,并在我的应用程序回收视图中显示它们,但现在我有问题,我想从一些特定的文件夹中提取所有PDF文件,并在我的应用程序的回收视图中显示它们,有没有可能的方法从特定的目录中提取?
这个功能将完全罚款和提取所有文件从存储,但我不想提取所有从外部存储我想这样做从一些特定的目录这个功能将给予我的所有pdf文件在我的外部存储列表我想在这个功能中做一些改变,但我不知道如何?

/**
 * reading SD card from this function
 *
 */
private List<PdfModel> ReadSDcard()
{
    List<PdfModel> myList = new ArrayList<>();
    String[] projection = {MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.DATE_ADDED,
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATE_MODIFIED
    };

    final String selection = MediaStore.Files.FileColumns.MIME_TYPE +" = ?";
    String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
    String[] selectionArgs = new String[]{pdf};

    Uri collection;
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.Q)
    {
//        collection = MediaStore.Downloads.getContentUri("external");
        collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
//        collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL+"/"+"Abbas_1122");
        Log.e(TAG, "ReadSDcard: path______________________________________________"+collection );
        myList.addAll( getListOfPdfFiles(collection, projection, selection, selectionArgs));
    }
    else
    {
//        collection = MediaStore.Files.getContentUri(Environment.getExternalStorageDirectory().getAbsolutePath()+"/myFolder_1122/");  _________"myFolder_1122" this is the folder which i have created
//        collection = MediaStore.Files.getContentUri("external");//this will work for fetching all files from external below API level 30
        collection = MediaStore.Files.getContentUri("//media//storage/emulated/0/Abbas_1122/");//this will work for fetching all files from external below API level 30
        Log.e(TAG, "ReadSDcard: path ______________________________________________ "+collection );
        Toast.makeText(this, "collection: "+collection.toString(), Toast.LENGTH_SHORT).show();

        myList.addAll( getListOfPdfFiles(collection, projection, selection, selectionArgs));

    }
    return myList;
}

    private List<PdfModel> getListOfPdfFiles(Uri collection, String[] projection, String selection, String[] selectArgs)
    {
        List<PdfModel> pdfList = new ArrayList<>();
        try {
            Cursor cursor = getApplicationContext().getContentResolver().query(collection, projection,selection, selectArgs,null);
            if (cursor.moveToFirst())
            {
                int columIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
                do {
                    try {
                        File file = new File(cursor.getString(columIndex));
                        String fileName = file.getName();
                        PdfModel pdfModel = new PdfModel(fileName, "129", 0, "pdf", file.getPath());
                        pdfList.add(pdfModel);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }while (cursor.moveToNext());
            }
            cursor.close();
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return pdfList;
    }
zzwlnbp8

zzwlnbp81#

我已经解决了这个问题这是非常容易的,但我不知道为什么我的头脑是不是工作上...首先你必须问一个权限从用户,如读取和写入外部存储,也要问管理外部存储,也要添加在manifist应用程序部分,你必须添加这一行...

android:requestLegacyExternalStorage="true"


private void fn_permission() {
    if ((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
            (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

        if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSIONS);
        }

        if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_PERMISSIONS);
        }
    } else {
        boolean_permission = true;
    }
}

如果用户已赠款权限,则以下功能将为您提供pdf文件列表

/**
 * reading from specific folder in Android */
private List<PdfModel> readFilesFromSpecificDir()
{
    List<PdfModel> list = new ArrayList<>();

    File filePath = new File(getDefaultStorageLocation());
    File[] fileList = filePath.listFiles();
    assert fileList != null;
    if (fileList.length!=0)
    {
        for (int i = 0; i<fileList.length; i++)
        {       //I have pdf model which will take these five arguments so you 
                   have to make your own
            list.add(new PdfModel(fileList[i].getName(),"123", 1.12, "pdf", fileList[i].getPath()));
            Log.e(TAG, "readFilesFromSpecificDir: wroking  list of files are given bellow ______________________________________________"+fileList[i].getName().toString() );
        }
    }
    else {
        Toast.makeText(getActivity(), "List empty...", Toast.LENGTH_SHORT).show();
    }

    return list;
}
//Doc_Reader
    public String getDefaultStorageLocation()  {
        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/YourFolderName/");
        Log.e(TAG, "getDefaultStorageLocation: __________________________________"+dir );
        if (!dir.exists()) {
            boolean isDirectoryCreated = dir.mkdir();
            if (!isDirectoryCreated) {
                Toast.makeText(getActivity() , "Directory cannot be created", 
                strong textToast.LENGTH_SHORT).show();
                Log.e("Error", "Directory could not be created");
            }
        }
    return dir.getAbsolutePath() + "/";
}

在这个问题中,我一直试图使用内容解析器获取特定的文件夹,以获取或检索他们的文件,并在我的应用程序回收视图中显示它们...但我失败了,所以这个方法是工作之前的API级别30或之后的API级别30...但请确保您已被授予权限特别感谢@blackapps采取interst和回复我来解决我的问题

相关问题