如何从指向PDF文档的URI获取文件路径

如何从指向PDF文档的URI获取文件路径

本文介绍了如何从指向PDF文档的URI获取文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我的代码打开了默认的下载视图,并且仅向我显示我下载的PDF.我选择了一个PDF文件,我得到了:

Right now my code opens up the default downloads view and it only shows me the PDFs I downloaded. I choose a PDF file and I get this:

我想要这个:

我的问题是如何在Android中做到这一点?

My question is how do I do this in Android?

我的代码:

public void PDF() {
    PDF = (Button) findViewById(R.id.FindPDFBtn);//Finds the button in design and put it into a button variable.
    PDF.setOnClickListener(//Listens for a button click.
        new View.OnClickListener() {//Creates a new click listener.
            @Override
            public void onClick(View v) {//does what ever code is in here when the button is clicked
                Intent intent = new Intent();
                intent.setType("application/pdf");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select a PDF "), SELECT_PDF);
            }
        }
    );
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //PDF
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PDF) {
            Uri selectedUri_PDF = data.getData();
            SelectedPDF = getPDFPath(selectedUri_PDF);
        }
    }
}

public String getPDFPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

推荐答案

在下面的getPDFPath方法中添加以下代码段:

Add this snippet below in your getPDFPath method:

public String getPDFPath(Uri uri){

     final String id = DocumentsContract.getDocumentId(uri);
     final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

     String[] projection = { MediaStore.Images.Media.DATA };
     Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     cursor.moveToFirst();
     return cursor.getString(column_index);
}

在您的情况下,此代码专门用于DownloadProvider中的文档,要进一步实施,请检查 Paul Burke的答案.我个人使用他的 aFileChooser库来避免这种问题.

In your case, this code is specifically for documents from DownloadProvider, for further implementation check Paul Burke's answer. I personally use his aFileChooser library to avoid this kind of problems.

这篇关于如何从指向PDF文档的URI获取文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:27