Skip to content Skip to sidebar Skip to footer

Search All .pdf File Present In The Android Device

How to search all .pdf and .doc file present in the Android device through programmatic way?

Solution 1:

Try using the below code, This will work for u.

publicvoidwalkdir(File dir) {
    StringpdfPattern=".pdf";

    File listFile[] = dir.listFiles();

    if (listFile != null) {
        for (inti=0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
                walkdir(listFile[i]);
            } else {
              if (listFile[i].getName().endsWith(pdfPattern)){
                                  //Do what ever u want

              }
            }
        }
    }    
}

EDIT

To search on the whole sdcard call this function using

walkdir(Environment.getExternalStorageDirectory());

Solution 2:

Have a look here

Basicly get a starting Directory and then call "list" with a filter(FilenameFilter) and then traverse sub directories. Not sure if there is a one function that does all this for you.

Solution 3:

Download source code from here (Open pdf file from sdcard 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;

publicclassMainActivityextendsAppCompatActivity {

ListView lv_pdf;
publicstatic ArrayList<File> fileList = newArrayList<File>();
PDFAdapter obj_adapter;
publicstaticintREQUEST_PERMISSIONS=1;
boolean boolean_permission;
File dir;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();

}

privatevoidinit() {

lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = newFile(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(newAdapterView.OnItemClickListener() {
@OverridepublicvoidonItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intentintent=newIntent(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 (inti=0; i < listFile.length; i++) {

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

} else {

booleanbooleanpdf=false;
if (listFile[i].getName().endsWith(“.pdf”)) {

for (intj=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;
}
privatevoidfn_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, newString[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);

}
} else {
boolean_permission = true;

getfile(dir);

obj_adapter = newPDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);

}
}

@OverridepublicvoidonRequestPermissionsResult(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 = newPDFAdapter(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;

publicclassPdfActivityextendsAppCompatActivityimplementsOnPageChangeListener,OnLoadCompleteListener {

PDFView pdfView;
IntegerpageNumber=0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;

@OverrideprotectedvoidonCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}

privatevoidinit(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}

privatevoiddisplayFromSdcard() {
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(newDefaultScrollHandle(this))
.load();
}
@OverridepublicvoidonPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@OverridepublicvoidloadComplete(int nbPages) {
PdfDocument.Metameta= pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);

}

publicvoidprintBookmarksTree(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 + “-“);
}
}
}
}

Solution 4:

Have a look Here

Change Extension of file like if you want all PDF file then extension ".pdf" use this to get all PDF file from device.

Solution 5:

Found this method in my old project, this function will get you pdf and its info

hope it will help you **ManageFIleInfoForRecycler is my custome class to store file info **

**"storage" pass 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);

        //ColumnString[] column = {MediaStore.Files.FileColumns.DATA,MediaStore.Files.FileColumns.TITLE};
        //WhereString where = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
        String[] args = newString[]{pdf};

        Cursor fileCursor = getApplicationContext().getContentResolver().query(table, column, where, args, null);

        String [] filesLists=newString[]{};
        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;

    }

Post a Comment for "Search All .pdf File Present In The Android Device"