2017-03-07 8 views
0

ボタンをクリックすると、pdfファイル(Rota)を開こうとしています。pdfボタンをクリックしようとしたときにAndroidアプリがクラッシュする

ファイルはassetsフォルダに保存されます。アプリがクラッシュし、ボタンをクリックすると閉じます。

私は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 /タグを取得しています:Rota.pdf(読み取り専用ファイルシステム) –

答えて

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

あなたのアプリケーションがクラッシュします:ここで

は、私が使用していたコードです。そして、あなたはlogcatのエラーを見るでしょう。あなたはgetFilesDir()はプライベートの内部メモリであるとして、このため、書き込みの外部記憶許可を要求する必要はありません

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

変更。

+0

ありがとう!それはうまくいった! –

+0

私はまた、コードの意図の部分を削除しました –

関連する問題