I have an APP that needs to open some PDF files (laws) that should come along with the application.
The idea is to call Intent
to open these PDF files by the PDF reader already installed on the phone. The files are in the assets. How do I open the PDF with the path of the file that is in the assets?
Here on the site was the following link, as an example:
link
Through the above example I did the following in MainActivity.java
:
package com.vdtecnologia.br.pdfassets;
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.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
Button btn1;
private String TAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openPDFFiles("AnexoI.pdf");
}
});
}
private void openPDFFiles(String AnexoI) //fileName is the pdf file name which is keep in assets folder. ex file.pdf
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "");
try {
in = assetManager.open(AnexoI);
out = openFileOutput(file.getName(), MODE_PRIVATE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + getFilesDir() + "/"+AnexoI), "application/pdf");
startActivity(intent);
}catch (RuntimeException ex){
Toast.makeText(MainActivity.this, "Não foi encontrado nenhum leitor de PDF no seu dispositivo", Toast.LENGTH_SHORT).show();
}
}
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);
}
}
}
But when you click the button it triggers the PDF reader and then returns to the APP with the following message:
The file could not be accessed. Please check the location or network and try again.