2013-11-22 219 views
0

我在assets文件夾中放置了pdf文件(bang.pdf),當點擊一個按鈕時,我需要打開並顯示來自assets文件夾的pdf。 的代碼是:從Android資產文件夾中打開pdf文件

package com.example.pdfviewer; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import android.app.Activity; 
import android.content.ActivityNotFoundException; 
import android.content.Context; 
import android.content.Intent; 
import android.content.res.AssetManager; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.Toast; 
public class MainActivity extends Activity { 
    Button but1; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     but1 = (Button)findViewById(R.id.but1); 

     but1.setOnClickListener(new OnClickListener() 

     { 

      @Override 
      public void onClick(View v) { 
       Toast.makeText(MainActivity.this,"hai" , Toast.LENGTH_SHORT).show(); 
       CopyReadAssets(); 

      } 
     }); 
    } 
    private void CopyReadAssets() 
    { 
     AssetManager assetManager = getAssets(); 
     InputStream in = null; 
     OutputStream out = null; 
     File file = new File(getFilesDir(), "bang.pdf"); 
     try 
     { 
      in = assetManager.open("bang.pdf"); 
      out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); 
      copyFile(in, out); 
      in.close(); 
      in = null; 
      out.flush(); 
      out.close(); 
      out = null; 
     } catch (Exception e) 
     { 
      Log.e("tag", e.getMessage()); 
     } 
     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setDataAndType(
       Uri.parse("file://" + getFilesDir() + "/bang.pdf"), 
       "application/pdf"); 
     startActivity(intent); 
    } 
    private void copyFile(InputStream in, OutputStream out) throws IOException 
    { 
     byte[] buffer = new byte[1024]; 
     int read; 
     while ((read = in.read(buffer)) != -1) 
     { 
      out.write(buffer, 0, read); 
     } 
    } 

    } 

但是當我點擊該按鈕,會顯示以下錯誤 錯誤: - android.content.ActivityNotFoundException:無活動處理意向{行動= android.intent.action.VIEW DAT =文件:///data/data/com.example.pdfviewer/files/bang.pdf典型值=應用程序/ PDF} 在mainifestfile: - 我提到 我已經在我的設備安裝Adobe Reader應用,仍然收到相同的錯誤信息。

請幫我在這

在此先感謝

+0

看看這裏:http://stackoverflow.com/questions/17085574/read-a-pdf-file-from-assets-folder –

回答

1

文件:// android_asset只在您的應用程序的工作原理

你將需要:

  1. 將文件複製到外部存儲或
  2. 將文件複製到內部存儲並使用ContentProvider使其可用於PDF視圖g應用程序

希望這會有所幫助。

0

我看到答案就在這裏給出:

Read a pdf file from assets folder

(這是幾乎一樣的問題,但更多的項目加入,許可WRITE_EXTERNAL_STORAGE缺少的要求)。 file://似乎沒問題,指的是外部存儲。

也許有更好的方法比複製外部(複製到內部存儲+由Siddharth Vyas建議的ContentProvider?)。

相關問題