Open PDF file from raw folder? - android

How can i open a PDFs file from raw folder?
This code for access PDFs file from SD card..
File file = new File(getFilesDir(), "teen_ebook.pdf");
try {
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.e("IR", "No exception");
}
else {
Toast.makeText(PdfActivity.this, "File NotFound",Toast.LENGTH_SHORT).show();
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(PdfActivity.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
}
But i want to access PDFs file from raw folder?
Any one here. Please suggests me.

You can not directly open PDF file from the raw folder. It requires PDFViewer application to open PDF file.
You will have to copy your PDF file into sdcard and then you can open to read it.
public void openPDF(){
copyFile(getResources().openRawResource(R.raw.hello_world);
, new FileOutputStream(new File(getFilesDir(), "yourPath/teen_ebook.pdf")));
File pdfFile = new File(getFilesDir(), "yourPath/teen_ebook.pdf");
Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "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);
}
}

Related

Share audio file from the res/raw folder thorugh Share Intent in Android

I'm trying to share an audio file from my res/raw folder. What I've done so far is:
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound); //parse path to uri
Intent share = new Intent(Intent.ACTION_SEND); //share intent
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share sound to"));
When I choose to share it on GMail, for example, it says something like "Failed to attach empty file". Looks like I'm not getting the right file path, so I'm basically sharing nothing. What am I doing wrong?
Any help would be much appreciated.
Copy the audio file from the resource to external storage and then share it:
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.sound);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Share sound"));
Add WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
What am I doing wrong?
Few apps handle android.resource Uri values correctly. Your choices are:
Drop the feature, or
Copy the data from the resource into a file, then use FileProvider, perhaps in conjunction with my LegacyCompatCursorWrapper, or
Use my StreamProvider, which can serve raw resources directly, or
Copy the data from the resource into a file, then use Uri.fromFile(), but this looks like it will stop working with the next version of Android, based on preliminary results from testing with the N Developer Preview
EDIT: It was causing a NullPointException. This is what was I doing:
File dest = Environment.getExternalStorageDirectory();
InputStream in = getResources().openRawResource(R.raw.sound);
try
{
OutputStream out = new FileOutputStream(new File(dest, "sound.mp3"));
byte[] buf = new byte[1024];
int len;
while ( (len = in.read(buf, 0, buf.length)) != -1){
out.write(buf, 0, len);
}
in.close();
out.close();
}catch (Exception e) {}
final Uri uri = FileProvider.getUriForFile(Soundboard.this, "myapp.folagor.miquel.folagor", dest); //NullPointerException right here!!
final Intent intent = ShareCompat.IntentBuilder.from(Soundboard.this)
.setType("audio/*")
.setSubject(getString(R.string.share_subject))
.setStream(uri)
.setChooserTitle(R.string.share_title)
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
The code was just fine. The only problem was that on the Manifest's permisions, I had "WRITE_EXTERNAL_STORAGE" instead of "android.permissions.WRITE_EXTERNAL_STORAGE". So I was not having permision to write in the external storage, which caused a FileNotFoundException due to the lack of permision. Now it works fine!

Android open PDF : File not found

I try to open a PDF in my application.
First, I create the PDF like that :
String filename = Environment.getExternalStorageDirectory().toString()+"/mypdf.pdf";
File file = new File(filename);
try {
FileOutputStream bos = new FileOutputStream(file);
bos.write(Base64.decode(base64, 0));
bos.flush();
bos.close();
} catch (IOException e) {
Log.e(TAG, "IOError with PDF");
e.printStackTrace();
}
Intent intent = new Intent(this, PdfActivity.class);
intent.putExtra("file", filename);
startActivity(intent);
The file is well created and readable, I can open this with ESExplorer application.
This file is located in /storage/emulated/0/myfile.pdf
in the PdfActivity I try to open the PDF :
Bundle extras = getIntent().getExtras();
String url = extras.getString("file");
File file = new File(url);
try {
if (file.exists()) {
Uri path = Uri.parse(url);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);
} else {
Toast.makeText(this, "File NotFound", Toast.LENGTH_SHORT).show();
}
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
file.exists() return true, Intent start, but my PDF reader says : "File not found"
I've added read and write permissions on external storage.
Does someone have any idea why it can't access to my file ?
objIntent.setDataAndType(url, "application/pdf");
use above line in your second snippest also declare String url as a global variable hope it will help you if it will not work try to use hardcode value of file path and see is it working or not ?
and are you sure file is exist? check this scenario tooo :)
I found the solution.
I've replace the Uri like that:
Uri path = Uri.fromFile(file);
And it works!

Android Reading PDF files from asstes folder

I have list of PDF files need to Place in asstes folder,my requirement is to read files from asstes and display it inside a listview.
if we click on each list item need to read respective PDF file
I have followed this blog http://androidcodeexamples.blogspot.in/2013/03/how-to-read-pdf-files-in-android.html
But here they have given reading a PDF files from External Storage Directory
I want to implement the same reading files from Asstes Folder
Could any one help How to implement the same example reading files from asstes?
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card.
Try out the below code to copy and read the file from assets folder:
//method to write the PDFs file to sd card
private void PDFFileCopyandReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "test.pdf");
try
{
in = assetManager.open("test.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
readFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/test.pdf"),
"application/pdf");
startActivity(intent);
}
private void readFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
Open the file from sdcard as below:
File file = new File("/sdcard/test.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Also provide a permission to write into your external storage in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Displaying PDF file with Adobe Reader

I created a class openPDF which takes a byte array as input and displays the PDF file with Adobe Reader. Code:
private void openPDF(byte[] PDFByteArray) {
try {
// create temp file that will hold byte array
File tempPDF = File.createTempFile("temp", ".pdf", getCacheDir());
tempPDF.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempPDF);
fos.write(PDFByteArray);
fos.close();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(tempPDF);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
}
When I pass the intend , the error from adobe reader is "Invalid file path". I read all other posts related to downloading and viewing PDF in android but dint help much. Any suggestions?
I think the issue is that other apps have no access to the files in your app's private data area (like the cache dir).
Candidate solutions:
changing the file's mode to MODE_WORLD_READABLE so that it can be read by other apps
...
String fn = "temp.pdf";
Context c = v.getContext();
FileOutputStream fos = null;
try {
fos = c.openFileOutput(fn, Context.MODE_WORLD_READABLE);
fos.write(PDFByteArray);
} catch (FileNotFoundException e) {
// do something
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
String filename = c.getFilesDir() + File.separator + fn;
File file = new File(filename);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
...
or write the pdf file to the /sdcard partition.
you can use android.os.Environment API to get the path, and remember to add the permission to your app's AndroidManifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Regards
Ziteng Chen
I made this code to open an especific .pdf file existing in Dowloads folder with Adobe's application
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
File pdf = new File(folder, "Test.pdf");
Uri uri = Uri.fromFile(pdf);
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.adobe.reader");
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
It works for me. So i guess your problem can be the temprorary file. Try to write the file to sdcard. To do this you will need add android.permission.WRITE_EXTERNAL_STORAGE to your AndroidManifest.xml.

I want my app to open pdf

my app downlods a pdf file from a link saving it to SD card, and it's working fine.. but what I'm struggeling at is I couldn't let my app views the pdf file..( although I've installed PDF viewer on my emulator)nothing happens after downloading the file...
here's my code for openning the pdf file
InputStream input = new BufferedInputStream(url.openStream());
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ "/myapp/download");
dir.mkdirs();
File file = new File(dir, "application/pdf");
FileOutputStream output = new FileOutputStream(file);
Use below code to open pdf file.
File pdfFile = new File("/mnt/sdcard/path_to_file/yourpdf.pdf");
if(pdfFile.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch(ActivityNotFoundException e) {
Toast.makeText(yourActivityClass.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(yourActivityClass.this, "File not found", Toast.LENGTH_LONG).show();
}
yourActivityClass.this is application context make it correct while testing above code.

Categories

Resources