以编程方式阅读pdf文件是错误的

时间:2012-02-29 09:20:42

标签: android

现在我正在做一个Android应用程序。我必须从sdcard读取一个文件。我在我的emulater中安装了adobe reader。我使用以下代码从sdcard运行该文件。

intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("/sdcard/samp.pdf"), "application/pdf");
    try{

        startActivity(intent);
    }
    catch (ActivityNotFoundException e) {
        System.out.println("5");
        // No application to view, ask to download one
        System.out.println("hai");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("No Application Found");
        builder.setMessage("Download one from Android Market?");
        builder.setPositiveButton("Yes, Please",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                        marketIntent
                                .setData(Uri
                                        .parse("market://details?id=com.adobe.reader"));
                        startActivity(marketIntent);
                    }
                });
        builder.setNegativeButton("No, Thanks", null);
        builder.create().show();
    }

我在sdcard.But中插入了一个名为sample.pdf的pdf,当我运行我的应用程序时,我收到“文件无法打开”。但我可以从emulater手动打开pdf。请帮我找出解决方案。

朋友们,我得到了解决方案。我删除了 intent.setDataAndType(Uri.parse("/sdcard/samp.pdf"), "application/pdf"); 并添加

 File file = new File("/sdcard/sample.pdf");
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");

现在它的工作。但现在我将sample.pdf文件夹放在我的assets文件夹中并编写以下代码。

 File file = new File("android.resource://com.pdftest/assets/sample");
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf"); 

我获取文件路径无效消息...

4 个答案:

答案 0 :(得分:3)

你有:

 File file = new File("android.resource://com.pdftest/assets/sample");

不应该是:

File file = new File("android.resource://com.pdftest/assets/sample.pdf");

答案 1 :(得分:2)

Uri必须包含的不仅仅是路径。如果你查看你的Uri的内容,它是空的。要拥有合适的Uri,请使用Uri.fromFile()

file = new File(Environment.getExternalStorageDirectory()+"/samp.pdf");
if (file.exists())
{
  Uri uri = Uri.fromFile(file);
  intent.setDataAndType(uri, "application/pdf");
  startActivity(intent);
}
else
{
Log.e("File not Exist","Check pdf File");
}

答案 2 :(得分:0)

您是否显示了正确的路径?可能是路径问题。

答案 3 :(得分:0)

只是看你有: sdcard / samp.pdf是文件名,你说你的文件名为:sample.pdf?

相关问题