2017-03-07 80 views
0

我試圖在單擊按鈕時打開PDF文件(Rota)。嘗試打開按鈕上的pdf時崩潰Android應用程序點擊

該文件存儲在資產文件夾中。當我點擊按鈕時,該應用程序崩潰並關閉。

我認爲我的CopyReadAssets方法有問題,但我不知道是什麼。

這裏是我使用的代碼:

import android.content.Intent; 
import android.content.res.AssetManager; 
import android.net.Uri; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.content.Context; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.File; 
import java.io.OutputStream; 


public class MainActivity extends AppCompatActivity { 
    Context context = this; 
    Button currentbutton; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

    currentbutton = (Button)findViewById(R.id.currentWeekbutton); 
    currentbutton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      CopyReadAssets(); 
     } 
    }); 
} 
private void CopyReadAssets() 
{ 
    AssetManager assetManager = getAssets(); 

    InputStream in; 
    OutputStream out; 

    File file = new File(getFilesDir(), "Rota.pdf"); 
    try 
    { 
     in = assetManager.open("Rota.pdf"); 
     out = openFileOutput(file.getName(), context.MODE_WORLD_READABLE); 

     copyFile(in, out); 
     in.close(); 
     in = null; 
     out.flush(); 
     out = null; 
     out.close(); 

    } catch (Exception e) { 
     Log.e("tag", e.getMessage()); 
    } 

    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(
      Uri.parse("File://" + getFilesDir() + "/rota.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); 
      } 
     } 

}

+0

在清單中我也有這個

+0

顯示日誌請 – Ibrahim

+0

現在只能得到這個E/tag:Rota.pdf(只讀文件系統) –

回答

0
out = openFileOutput(file.getName()); 

這裏你的應用程序會崩潰。你會看到logcat中的錯誤。

更改爲

out = new FileOutputStream(file.getAbsolutePath()); 

你不必請求該寫入外部存儲權限爲getFilesDir()是私有的內部存儲器。

+0

謝謝!這工作! –

+0

我也刪除了代碼的意圖部分 –

相關問題