Android - Display PDF from server - android

Trying to display a PDF received from server but getting "Media not found error"
First I convert String to byte array:
byte[] data = Base64.decode(stringData, Base64.DEFAULT);
Then I write the byte[] to a file:
String path = getFilesDir() + "/myfile.pdf";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(article.getFileDataBytes());
stream.close();
Then I try to display PDF:
Uri path2 = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path2, "application/pdf");
startActivity(intent);
But after calling startActivity I receive the "Media not found error"
I'm not sure what's wrong no exceptions are thrown when writing the file

You are writing the file to internal storage. No third-party apps have access to your internal storage directly. Use FileProvider to make the PDF available to third-party apps.
This sample app does pretty much what you need, except that I get the starting PDF from an asset.

Related

Share song on WhatsApp, always ends in "failed to send" message

I'm getting an input stream from a webservice and converting it to byte array so i can create a temporary file and play it using MediaPlayer (it is a .mp3). The problem is that i want to share the song on whatsapp, but i get the "failed to send" message whenever i try.
This is how i get and play the song:
if (response.body() != null) {
byte[] bytes = new byte[0];
try {
bytes = toByteArray(response.body().byteStream());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.reset();
try {
File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3);
fos.close();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
}
catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
mediaPlayer.start();
This and a few similar ways is how i have tried to share it:
String sharePath = Environment.getExternalStorageDirectory().getPath()
+ "/tempfile.mp3";
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
The song is playing just fine and i have included the permission both for reading and writing in the external storage but i need help to share the song, be it as bytes or as file or as whatever works, please.
You will need to change from
File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
to
File tempMp3 = new File(Environment.getExternalStorageDirectory() + "/"+ getString(R.string.temp_file) + getString(R.string.dot_mp3)); //<- this is "tempfile" and ".mp3"
then you can share it like this
String sharePath = tempMp3.getAbsolutePath();
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, getString(R.string.share_song_file)));
The main problem was that where you were storing the file could NOT be shared with other apps, was only accessible from your own, since the getCacheDir() method is used to create cache files rather than storing data in files persistently, and is sort of private to the application (and createTempFile() generates random numbers at the end of the file's name, so you wouldn't be able to hard code the correct path like that).
Also, this solution makes use of the permissions you included (accessing external storage).

Attach inputstream to email

I have an android apk expansion file and in there are some PDF's.
In the official documentation they access the files inside the .obb via Inputstream. I am able to access the files inside the .obb via the inputstream.
Now I want to attach one of the files to an email with Intent. The E-Mail Intent works perfectly fine with files from the assets, so the problem is attaching the Inputstream.
How can I attach the PDF into the mail directly from the .obb?
Solved it!
You have to convert the Inputstream to a Temorary File, get the Uri of that file and attach it to the email Intent.
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("application/pdf");
try {
ZipResourceFile expansionFile = new ZipResourceFile("Path to .obb file");
InputStream fileStream = expansionFile.getInputStream("Path inside .obb");
String downloadordner = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); //used for temp storage
File tempFile = new File(downloadordner+"/"+"filename.pdf");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(fileStream, out);
Uri theUri = Uri.fromFile(tempFile);
i.putExtra(Intent.EXTRA_STREAM, theUri);
startActivity(Intent.createChooser(i, "PDF versenden..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(preisliste.this, "Es wurde kein E-Mail Client gefunden.", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
Log.v("Datei nicht gefunden","Main Expansion");
}

Run apk from inside android application

I am thinking if there is a way to run an apk file and start the installation procedure from inside an already installed application.
I know that the following code opens an apk file:
File apkFile = new File(path + file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
startActivity(intent);
but how can I find the apk(path) when it is for example inside the resources folder of the application's folder? Could this be done?
It would depend on whether you have your phone rooted or not, but assuming it isn't, you can put your apk file inside raw folder, open it and then run that intent. It should look something like this:
File tempFile = Utils.openResourceFile(context, R.raw.yourapk, "yourapkname.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(tempFile),"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Utils.java
public static File openResourceFile(Context context, int resFile, String tempFileName) throws IOException{
InputStream in = context.getResources().openRawResource(resFile);
byte[] b = new byte[in.available()];
in.read(b);
FileOutputStream fout = context.openFileOutput(tempFileName, Context.MODE_WORLD_READABLE);
fout.write(b);
fout.close();
in.close();
return context.getFileStreamPath(tempFileName);
}

Android - Share file from sd using bluetooth

Im trying to send a file from my SD using Bluetooth. I'm using Share intent, I wanna send a file from my SD (.mp3). ok when I open the share menu, I can send file to email, dropbox, whatsapp, but if I select Bluetooth, My device shows a message "File null was not sent to ..."
My steps are:
1. Create SEND intent.
2. Copy my file from res/raw to SD
3. Add my file to putExtra
4. Delete the file (is temporal file)
The code:
Intent shareIntent=new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("audio/mp3");
//Copiamos archivo a compartir en la sd
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = sonidoActual+"-temp.mp3";
File newSoundFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
////
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(newSoundFile.getAbsolutePath())/*Uri.parse("file:///sdcard/"+fileName)*//*Uri.parse("android.resource://com.genaut.instantbuttonsfreak/raw/"+texto)*/);
startActivity(Intent.createChooser(shareIntent,getString(R.string.share)));
//
newSoundFile.delete();
Anybody can help me with this? I read a lot but not found a working method, sorry my english.
I think your file is not release by File-I/O.
SO.. try flush() the FileOutPutStream.. like,
fos.flush();
fos.close();
then, use Uri.fromFile(File file) for uri to pass with Intent.. But before passing Uri to Intent just check whether file is exist or not..
like,
if(newSoundFile.exist())
{
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(newSoundFile))
startActivity(Intent.createChooser(shareIntent,getString(R.string.share)));
newSoundFile.delete();
}

How to store downloaded images in to android SD card

Hi I am developing app which downloads the images from the web site
and then i am displaying them as slide show. Now I want save the
downloaded images into my SD card please help me.
My current attempt is:
File imageFileFolder = new File(Environment
.getExternalStorageDirectory(), "test");
imageFileFolder.mkdir();
File imageFileName = new File(imageFileFolder, date
+ pBean.getAuthorName());
InputStream fis = pBean.getInputStream();
byte[] data = new byte[fis.available()];
fis.read(data);
FileOutputStream fos = new FileOutputStream(imageFileName);
fos.write(data);
fos.close();
fis.close();
There are lot of examples available for this
Check this post
Lazy load of images in ListView
and link
http://open-pim.com/tmp/LazyList.zip
In your AndroidManifest.xml you'll need to add the permission to write
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Then just get get the path to your filename and make sure your directories exist before trying to write the file to the sdcard.
String imageFileName = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/somedirectory/imagename.jpg"

Categories

Resources