繁体   English   中英

尝试在单击按钮时打开pdf时崩溃的Android应用

[英]Crashing Android app when trying to open a pdf on button click

单击按钮时,我正在尝试打开pdf文件(Rota)。

该文件存储在资产文件夹中。 当我单击按钮时,应用程序崩溃并关闭。

我认为我的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);
            }
        }

}

  out = openFileOutput(file.getName());

在这里,您的应用将崩溃。 您将在logcat中看到错误。

改成

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

您不必为此请求写外部存储权限,因为getFilesDir()是私有内部存储器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM