I am developing an Android app. I keep a PDF data in MYSQL database as blob type. I am sending as base64 to Android app. How can I show the pdf in Android app?
As you have the yourBase64String with you, you can convert it to byte array and then save it as file.
FileOutputStream fos = null;
try {
if (yourBase64String != null) {
fos = context.openFileOutput("myPdf.pdf", Context.MODE_PRIVATE);
byte[] decodedString = android.util.Base64.decode(yourBase64String , android.util.Base64.DEFAULT);
fos.write(decodedString);
fos.flush();
fos.close();
}
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
Now after this open this PDF file
Uri path = Uri.fromFile(new File(myPdf.pdf));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
Add this permission in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Related
I'm new to android studio and I'm a beginner. I want to build an app that contains 2 or 3 apk files inside the app itself - not in device storage - and make a single button to prompt to install all of them. Is that possible?!
Use this to save file to storage after requesting necessary permission : Write_External_Storage
private void copyAsset(String filename){
String dirPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
File dir = new File(dirPath);
if(!dir.exists()){
dir.mkdirs();
}
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open( filename);
File outFile = new File(dirPath, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
} catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show();
} finally {
if (in != null){
try{
in.close();
} catch (IOException e){
e.printStackTrace();
}
}
if (out != null){
try{
out.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
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);
}
}
And finally use this to install:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new
File(Environment.getExternalStorageDirectory().getAbsolutePath + "/MyFiles/" +
"appName.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Make sure to request permessions : REQUEST_INSTALL_PACKAGES and READ EXTERNAL STORAGE
I'm trying to pass the screenshot of screen with an explicit intent but the screen shows black screenshot(refer image here). As soon as i click share, a toast appears saying sending failed. Here's the code to capture screenshot and send it to other app:
public void getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
f = new File(this.getFilesDir(), "screenshotFile");
try {
if (!f.exists())
f.createNewFile();
} catch (IOexception e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This code sends the data to whatsapp:
public void shareWhatsapp(View view) {
try {
myVib.vibrate(50);
getScreenShot(view);
//String fileName = "screenshotFile";
//Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
try {
intent.setPackage("com.whatsapp");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "App not installed", Toast.LENGTH_SHORT).show();
}
//TODO: APP CAN CRASH HERE
if (position > 0) {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(position - 1) + ": " + Links.get(position - 1)); //position problems
}
} else {
try {
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f);
} catch (Exception e) {
e.printStackTrace();
} finally {
intent.putExtra(Intent.EXTRA_TEXT, Titles.get(0) + ": " + Links.get(0)); //position problems
}
}
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Can someone help me with this?
First, you are writing the file to internal storage. Third-party apps do not have access to your app's internal storage.
Second, you are using Uri.fromFile(), which is starting to be discontinued.
Your safest long-term course of action is to have a ContentProvider serve your file from its location on internal storage, then use a Uri associated with that ContentProvider.
I am Recording a video using my android application.when i am trying to read the video from the path after recording i did'nt get the full recorded file.
but after some time i can read the full file.i don't know what is the problem?
please help.
Here is my code
try {
videoFile = getOutputMediaFile(MEDIA_TYPE_VIDEO);
videothumb = new File(getOutputMediaThumbFile(MEDIA_TYPE_VIDEO), videoFile.getName());
db.insertFileInfo(videoFile.getName(), 0, videoFile.length(), 0, "video/mp4");
if (videoFile == null) {
Log.d("", "Error creating media file, check storage permissions: ");
safeToTakePicture = true;
return null;
}
videothumb.createNewFile();
videoFile.createNewFile();
Thread.sleep(10000);
upVFile = new File(videoFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(videoFile);
FileOutputStream ftos = new FileOutputStream(videothumb);
thumb = Bitmap.createScaledBitmap(bmv, 200, 200, false);
thumb.compress(Bitmap.CompressFormat.JPEG, 90, ftos);
ftos.flush();
ftos.close();
bmv.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmv.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
baos.close();
String encodedImage = new String(Base64.encodeBase64(b));
editor.putString("image_data", encodedImage);
editor.commit();
editor.putString(IMAGE_NAME, videoFile.getName());
editor.commit();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
write a method for refreshing gallery
private void refreshGallery(File file){
Intent mediaScanIntent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
I am creating a game, and trying to allow the user to share their win via text/facebook/etc. I am using the code below to grab an image from my res/drawable folder. I am pretty sure I am doing it right, but my app keeps crashing after I choose the send method (ex. facebook). Any help would be greatly appreciated.
Intent ShareIntent = new Intent(android.content.Intent.ACTION_SEND);
ShareIntent.setType("image/jpeg");
Uri winnerPic = Uri.parse("android.resource://com.poop.pals/" + R.drawable.winnerpic);
ShareIntent.putExtra(Intent.EXTRA_STREAM, winnerPic);
startActivity(ShareIntent);
Android's resources are only accessible to your app via the resource apis, there is no regular file on the filesystem you can open in other ways.
What you can do is to copy the file from the InputStream you can get to a regular file in a place that is accessible to other apps.
// copy R.drawable.winnerpic to /sdcard/winnerpic.png
File file = new File (Environment.getExternalStorageDirectory(), "winnerpic.png");
FileOutputStream output = null;
InputStream input = null;
try {
output = new FileOutputStream(file);
input = context.getResources().openRawResource(R.drawable.winnerpic);
byte[] buffer = new byte[1024];
int copied;
while ((copied = input.read(buffer)) != -1) {
output.write(buffer, 0, copied);
}
} catch (FileNotFoundException e) {
Log.e("OMG", "can't copy", e);
} catch (IOException e) {
Log.e("OMG", "can't copy", e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
// ignore
}
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
// ignore
}
}
}
I have to store data text to SD Card.
This is my code :
try {
File myFile = new File(Environment.getExternalStorageDirectory()+"/mnt/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
In AndroidMainfest i have :
<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I don't understand Why it don't work ?
In Toast reported error :Permission denied?
Please help me .
You can also try this https://github.com/uberspot/AndroidStorageUtils it's a wrapper class/package that makes storage usage in android a bit easier. :) It has a "saveStringOnExternalStorage" method as well.
Try this code must solve issues...
try{
String filename = "filename.txt";
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if(!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = txtData.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}