简体   繁体   中英

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

I'm trying to open a pdf file (Rota) when clicking a button.

The file is stored in the assets folder. The app crashes and closes when I click the button.

I think there is a problem with my CopyReadAssets method but I cant tell what.

Here is the code I am using:

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());

Here your app will crash. And you will see the errors in the logcat.

Change to

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

You do not have to request a write external storage permission for this as getFilesDir() is private internal memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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