How can I search all .pdf and .doc files present in the Android device through a programmatic way?
5 Answers
Try using the below code. This will work for you.
public void walkdir(File dir) {
String pdfPattern = ".pdf";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pdfPattern)){
//Do whatever you want
}
}
}
}
}
To search on the whole SD card, call this function using:
walkdir(Environment.getExternalStorageDirectory());

- 30,738
- 21
- 105
- 131

- 5,552
- 4
- 40
- 50
-
1Its very slow. Do you know anything that get quicker. – Shabbir Dhangot Jan 07 '17 at 07:33
-
Environment.getExternalStorageDirectory() is deprecated for API29 and above. Is there any alternative? – Burak Dizlek Mar 03 '21 at 05:38
-
@BurakDizlek you can check out [my answer](https://stackoverflow.com/questions/13361024/how-to-get-the-internal-and-external-sdcard-path-in-android/70879069#70879069) to get internal and external directories. – Atakan Yildirim Jan 28 '22 at 20:27
-
Not working on Android 11 – Hoàng Vũ Anh Feb 26 '22 at 08:29
Download source code from here (Open pdf file from SD card in android programmatically)
Add this Dependency in your Gradle file:
compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’
MainActivity.java:
package com.pdffilefromsdcard;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);
Log.e(“Position”, i + “”);
}
});
}
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()) {
getfile(listFile[i]);
}
else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
}
else {
}
}
if (booleanpdf) {
booleanpdf = false;
}
else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
}
else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}
else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();
}
}
}
}
PdfActivity.java:
package com.pdffilefromsdcard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.io.File;
import java.util.List;
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}

- 30,738
- 21
- 105
- 131

- 2,104
- 22
- 23
-
Presumably, it is self-plagiarism. It is relatively simple to make code render properly in WordPress. – Peter Mortensen Dec 29 '22 at 21:11
Have a look at File, list.
Basically, get a starting Directory, call "list" with a filter(FilenameFilter), and then traverse sub directories. I am not sure if there is a one function that does all this for you.

- 30,738
- 21
- 105
- 131

- 1,565
- 3
- 21
- 38
Have a look at Stack Overflow question How can I get all audio files from the SD card on Android?.
Change the extension of the file like if you want all PDF files then extension ".pdf". Use this to get all PDF files from the device.

- 30,738
- 21
- 105
- 131

- 967
- 15
- 29
I found this method in my old project. This function will get you the PDF file and its information.
ManageFIleInfoForRecycler is my custom class to store the file information.
"storage" passes as "external".
public ArrayList<ManageFIleInfoForRecycler> fileList(String storage) {
ArrayList< ManageFIleInfoForRecycler > fileInfo = new ArrayList<>();
// Can give any file type, "doc", "pdf", etc.
String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
int j = 0;
Uri table = MediaStore.Files.getContentUri(storage);
// Column
String[] column = {MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.TITLE};
// Where
String where = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String[] args = new String[]{pdf};
Cursor fileCursor = getApplicationContext().getContentResolver().query(table, column, where, args, null);
String [] filesLists = new String[]{};
while (fileCursor.moveToNext()) {
int pathString = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
int nameIndex = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE);
String path = fileCursor.getString(pathString);
String name = fileCursor.getString(nameIndex);
ManageFIleInfoForRecycler temp = new ManageFIleInfoForRecycler();
temp.filePath = path;
temp.fileName = name;
fileInfo.add(temp);
}
return fileInfo;
}

- 30,738
- 21
- 105
- 131

- 606
- 8
- 12