Search all .pdf files present in the Android device
How ca开发者_如何学编程n I search all .pdf and .doc files present in the Android device through a programmatic way?
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());
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.
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 + “-“);
}
}
}
}
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.
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;
}
精彩评论