user5134138
user5134138

Reputation:

how to list all pdf files in my android device

I found this code about how to get all my Images.

Can someone tell me how can I get only .pdf files in internal storage and external storage?

final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    //Stores all the images from the gallery in Cursor
    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    //Total number of images
    int count = cursor.getCount();

    //Create an array to store path to all the images
    String[] arrPath = new String[count];

    for (int i = 0; i < count; i++) {
        cursor.moveToPosition(i);
        int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        //Store the path of the image
        arrPath[i]= cursor.getString(dataColumnIndex);
        Log.i("PATH", arrPath[i]);
    } 

Upvotes: 8

Views: 18451

Answers (5)

Za101
Za101

Reputation: 521

I think this is the most concise method if you are using Kotlin

val ROOT_DIR = Environment.getExternalStorageDirectory().absolutePath
val ANDROID_DIR = File("$ROOT_DIR/Android")
val DATA_DIR = File("$ROOT_DIR/data")
File(ROOT_DIR).walk()
               // befor entering this dir check if
               .onEnter{ !it.isHidden // it is not hidden
                         && it != ANDROID_DIR // it is not Android directory
                         && it != DATA_DIR // it is not data directory
                && !File(it, ".nomedia").exists() //there is no .nomedia file inside
               }.filter { it.extension == "pdf" }
               .toList()

You could do similar thing with java8 streams or maybe RxJava

Upvotes: 3

Pierre
Pierre

Reputation: 9052

You can use the following to list PDF documents (this will not list unknown PDFs on the device)

// Use android.provider.MediaStore

String[] projection = {
    MediaStore.Files.FileColumns._ID,
    MediaStore.Files.FileColumns.MIME_TYPE,
    MediaStore.Files.FileColumns.DATE_ADDED,
    MediaStore.Files.FileColumns.DATE_MODIFIED,
    MediaStore.Files.FileColumns.DISPLAY_NAME,
    MediaStore.Files.FileColumns.TITLE,
    MediaStore.Files.FileColumns.SIZE,
};

String mimeType = "application/pdf";

String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')";
String orderBy = MediaStore.Files.FileColumns.SIZE + " DESC";
Cursor cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"),
                                           projection,
                                           whereClause,
                                           null,
                                           orderBy);

If you want to have more than just PDF files, like DocX you can alter the where clause a bit to suite your needs:

String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')"
          + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd%'"

Then loop through the cursor to retrieve the documents:

int idCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
int mimeCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE);
int addedCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_ADDED);
int modifiedCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED);
int nameCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME);
int titleCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
int sizeCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE);

if (cursor.moveToFirst()) {
    do {
        Uri fileUri = Uri.withAppendedPath(MediaStore.Files.getContentUri("external"), cursor.getString(idCol));
        String mimeType = cursor.getString(mimeCol);
        long dateAdded = cursor.getLong(addedCol);
        long dateModified = cursor.getLong(modifiedCol);
        // ...
    } while (cursor.moveToNext());
}

Upvotes: 5

Yoav Feuerstein
Yoav Feuerstein

Reputation: 1975

You should be able to list all of them through Android's MediaStore.Files, without manually going through all the device's folders.

For example:

String selection = "_data LIKE '%.pdf'"
try (Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Files.getContentUri("external"), null, selection, null, "_id DESC")) {
    if (cursor== null || cursor.getCount() <= 0 || !cursor.moveToFirst()) {
        // this means error, or simply no results found
        return;
    }
    do {
        // your logic goes here
    } while (cursor.moveToNext());
}

(Note: this topic might be a duplicate of another, older question, but it doesn't have an accepted answer so can't flag it)

Upvotes: 6

Maddy Sharma
Maddy Sharma

Reputation: 4956

You can try this : 1.)

private ListView mListView;
private ArrayList<AttachmentModel> mAttachmentList = new ArrayList<>();
private ArrayList<File> fileList = new ArrayList<File>();
mListView = (ListView)findViewById(R.id.listAttachments);
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
getfile(dir );
setAdapter();

2.)

public ArrayList<File> getfile(File dir) {
        File listFile[] = dir.listFiles();
        if (listFile != null && listFile.length > 0) {
            for (int i = 0; i < listFile.length; i++) {

                if (listFile[i].isDirectory()) {
                    fileList.add(listFile[i]);
                    getfile(listFile[i]);

                } else {
                    if (listFile[i].getName().endsWith(".pdf")
                            || listFile[i].getName().endsWith(".xls")
                            || listFile[i].getName().endsWith(".jpg")
                            || listFile[i].getName().endsWith(".jpeg")
                            || listFile[i].getName().endsWith(".png")
                            || listFile[i].getName().endsWith(".doc"))
                    {
                        fileList.add(listFile[i]);
                        mAttachmentList.add(new AttachmentModel(listFile[i].getName()));
                    }
                }
            }
        }
        return fileList;
    }

3.)

private void setAdapter()
    {
        AttachmentAdapter itemsAdapter = new AttachmentAdapter(AttachmentFileList.this);
        ArrayList<AttachmentModel> list = new ArrayList<>();
        itemsAdapter.setData(mAttachmentList);
        mListView.setAdapter(itemsAdapter);
    }

Upvotes: 2

Moubeen Farooq Khan
Moubeen Farooq Khan

Reputation: 2885

possible solution can be go to every folder and check if .pdf exists or not if yes the you can do whaterver you want to do with that file

public void Search_Dir(File dir) {
  String pdfPattern = ".pdf";

File FileList[] = dir.listFiles();

if (FileList != null) {
    for (int i = 0; i < FileList.length; i++) {

        if (FileList[i].isDirectory()) {
            Search_Dir(FileList[i]);
        } else {
          if (FileList[i].getName().endsWith(pdfPattern)){
                              //here you have that file.

          }
        }
    }
  }    
}

and function call will be

Search_Dir(Environment.getExternalStorageDirectory());

Upvotes: 9

Related Questions