2012-02-29 34 views
0

現在我正在做一個Android應用程序。我必須從sdcard.I讀取文件,在我的emulater中安裝了adobe reader。並且我使用以下代碼從sdcard運行該文件。閱讀pdf文件編程方式是給錯誤

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文件夾放在我的資產文件夾中,並編寫下面的代碼。

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

,我得到的文件路徑無效的消息......

回答

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"); 
} 
+0

我做了一些改變A和現在的工作......我removeintent.setDataAndType(Uri.parse(「/ SD卡/ samp.pdf「),」application/pdf「);並添加File file = new File(「/ sdcard/sample.pdf」); Uri uri = Uri.fromFile(file); intent.setDataAndType(uri,「application/pdf」); – sarath 2012-02-29 09:31:25

+0

嗨..現在它的工作爲SD卡,但不是我放在資產文件夾的文件。如何從assets文件夾中讀取相同的文件。我給了File file = new File(「/ sdcard/sample.pdf」); Uri uri = Uri.fromFile(file); intent.setDataAndType(uri,「application/pdf」);但沒有找到文件路徑 – sarath 2012-02-29 09:39:44

+0

雅..我把我的文件到資產文件夾,並寫入文件文件=新文件(「android.resource://com.pdftest/assets/sample」); ..但其給出的路徑不發現... – sarath 2012-02-29 09:49:38

0

您是否顯示正確的路徑?可能是路徑問題。

0

只是看看你有: SD卡/ samp.pdf是文件名,你說你有文件名爲:sample.pdf?

+0

我插入了樣本和樣本 – sarath 2012-02-29 09:29:40

3

您有:

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

它不應該是:

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