Java: How to automatically open pdf after Download - java

I've been looking for various tutorials but no one can solve my case. I hope here is something that can make me understand, about how to open PDF file automatically after finished download from database to android.
This is my download script.
#Override
public void onBindViewHolder(HolderData holder, int position) {
final ModelData md = mItems.get(position);
holder.txtname.setText(md.getName());
holder.txtwaktu.setText(md.getWaktu());
//Proses Downloading
holder.relativeLayoutMateri.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uri = String.valueOf(Uri.parse("http://192.168.43.144/MLearning/crud/"+md.getPath()));
dm = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
longid = dm.enqueue(request);
Toast.makeText(context, md.getName()+" Berhasil Di Download"+md.getPath(), Toast.LENGTH_SHORT).show();
}
});
}

Here is the solution please use ACTION_VIEW Intent to open all you need the path of downloaded pdf.
private static String filepath = Environment.getExternalStorageDirectory().getPath()+"/myfile.pdf";
File file = new File(filepath);
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);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.d(TAG,e.getMessage());
}
}

Related

Check if a file exists in Android

Android/Java, API level 12.
I'm trying to check if a .zip file exists in the Downloads folder. If it doesn't exist then I'm downloading it from the internet using DownloadManager. For the purposes of testing I'm running my checkIfFileExists immediately after the onReceive method of the DownloadManager, subject to the download being successful. My issue is that checkIfFileExists is returning false every time, even after I've just downloaded the file and I've checked manually that it does exist.
The relevant code is below.
DownloadManager dm;
long queueid;
String filename = "myfile.zip", url = "http://myurl/", uriString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
{
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queueid);
Cursor c = dm.query(req_query);
if (c==null)
{
Toast.makeText(context, "Download not found!", Toast.LENGTH_SHORT).show();
}
else
{
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnIndex))
{
uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Toast.makeText(context, "Download finished.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, uriString, Toast.LENGTH_LONG).show();
checkIfFileExists();
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClickDownload(View v) // this method seems to be working with no issues.
{
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, filename);
queueid = dm.enqueue(request);
}
private boolean checkIfFileExists()
{
File file = new File(uriString);
if(file.exists())
{
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}
I was expecting if(file.exists()) to evaluate to true since the file does exist.
What actually happens is if(file.exists()) always evaluates as false.
Can anyone see what I'm doing wrong?
Change your method like this.:
private boolean checkIfFileExists(String zipName /*ex: fileName.zip*/) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), zipName);
if(file.exists()) {
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}

Reading Database File from External Storage

So, this program downloads a file from firebase storage,
my downloading code is:
private void downloadFiles(Context context, String fileName, String destinationDirectory, String url) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, String.valueOf(destinationDirectory), fileName);
downloadManager.enqueue(request);
}
public void downloading(final String name) {
downloadRef = storage.getInstance().getReference().child(name);
downloadRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFiles(Main2Activity.this, name, getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main2Activity.this, "Failed!!!", Toast.LENGTH_LONG).show();
}
});
}
and then I want to use this database so I tried to open it with:
database = SQLiteDatabase.openDatabase(myPath, null, 0);
How can I solve this one? It would be really helpful guys.
I thought your problem was accessibility.
That's why I brought a activity back to get permission from the user.
You test this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("name", arrayList.get(position));
startActivity(intent);
}
}
});
You are using Environment.getExternalStorageState() which returns the current state of the primary shared/external storage media. It cannot be used to get the path as string of any file. Use context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) to get the string value of the path to the Download directory.

its taking the screenshot but not showing in gallery

It's taking the screenshot but not showing in gallery when I check the device storage there are screenshot files but when I try to click them it says unable to find app to open this file.
I have to share the ui of my application as an image
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
store(bitmap,"share_image");
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public void store(Bitmap bm, String fileName){
dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
shareImage(file);
} catch (Exception e) {
e.printStackTrace();
}
}
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No App Available", Toast.LENGTH_SHORT).show();
}
}
You are calling your file share_image. It has no extension, so the system will treat it as a blank, basic file.
As you are using png compression, add ".png" to the file name.
store(bitmap,"share_image.png");

Android open downloaded file

I have a question about downloading a pdf file and opening it with an pdf reader application installed on the phone. I'm new to android and working my way up but got stuck on this part.
So what i have now:
I have an activity that for now starts downloading a pdf file and tries to open is with an intent. For now everything is static so thats why i have a set url.
private void DownloadFile(){
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse("http://awebiste.adomain/afile.pdf");
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("My Data Download");
request.setDescription("Android Data download using DownloadManager.");
request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"test.pdf");
Long downloadReference = downloadManager.enqueue(request);
if (downloadReference != null){
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.parse(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/test.pdf"), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.v("OPEN_FILE_PATH", getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/test.pdf");
startActivity(target);
} else {
//TODO something went wrong error
}
}
Now the file is downloaded and saved in the application folder under /storage.sdcard0/Android/data/<application>/files/download and from the documents browser the file can be opent. But when i use the intent at the button of my code i get a toast that the file can not be opent. After some searching on google i think its a permission problem because these files are private to the application. So how do I make these files public?
Here's How I did it after a long day of search,Your code helped me a little to solve it:
String name;
DownloadManager mManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_interview);
Button down = (Button) findViewById(R.id.download);
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
down();
}
});
}
public void down() {
mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, name + "CV.pdf")
.setDescription("Download in progress").setMimeType("pdf");
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(broadcast, intentFilter);
}
public void showPdf() {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Download/" + name + "CV.pdf");//name here is the name of any string you want to pass to the method
if (!file.isDirectory())
file.mkdir();
Intent testIntent = new Intent("com.adobe.reader");
testIntent.setType("application/pdf");
testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
testIntent.setDataAndType(uri, "application/pdf");
startActivity(testIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastReceiver broadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPdf();
}
};

MediaStore.EXTRA_OUTPUT renders data null, other way to save photos?

Google offers this versatile code for taking photos via an intent:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
The problem is that if you're like me and you want to pass the photos as extras, using EXTRA_OUTPUT seemingly runs off with the photo data and makes subsequent actions think the intent data is null.
It appears this is a big bug with Android.
I'm trying to take a photo then display it as a thumbnail in a new view. I'd like to have it saved as a full sized image in the user's gallery. Does anyone know a way to specify the image location without using EXTRA_OUTPUT?
Here's what I have currently:
public void takePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "JoshuaTree");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("JoshuaTree", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
handleSmallCameraPhoto(data);
}
}
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", mImageBitmap);
startActivity(displayIntent);
}
}
If you specified MediaStore.EXTRA_OUTPUT, the image taken will be written to that path, and no data will given to onActivityResult. You can read the image from what you specified.
See another solved same question here: Android Camera : data intent returns null
Basically, there are two ways to retrieve the image from Camera, if you use to send a captured image through intent extras you cannot retrieve it on ActivityResult on intent.getData() ' because it saves the image data through extras.
So the idea is:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
And retrieving it on ActivityResults checking the retrieved intent:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (intent.getData() != null) {
ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(intent.getData(), "r"); 
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} else {
Bitmap imageRetrieved = (Bitmap) intent.getExtras().get("data");
}
}
}
}
Here is how you can achieve what you want:
public void onClick(View v)
{
switch(v.getId())
{
case R.id.iBCamera:
File image = new File(appFolderCheckandCreate(), "img" + getTimeStamp() + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_RESULT);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case CAMERA_RESULT:
if(resultCode==RESULT_OK)
{
handleSmallCameraPhoto(uriSavedImage);
}
break;
}
}
private void handleSmallCameraPhoto(Uri uri)
{
Bitmap bmp=null;
try {
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", bmp);
startActivity(displayIntent);
}
private String appFolderCheckandCreate(){
String appFolderPath="";
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage.canWrite())
{
appFolderPath = externalStorage.getAbsolutePath() + "/MyApp";
File dir = new File(appFolderPath);
if (!dir.exists())
{
dir.mkdirs();
}
}
else
{
showToast(" Storage media not found or is full ! ");
}
return appFolderPath;
}
private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS").format(cal.getTime());
return timeString;
}
Edit:
Add these to Manifest:
Starting Api 19 and above READ_EXTERNAL_STORAGE should be declared explicitly
*<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />*
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to you manifest.
Try this one android.provider.MediaStore.EXTRA_OUTPUT hope will solve your bug. The following code works for me:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
I was facing same problem, every time getting null while retrieving data on other activity with getIntent().getData() then solved by writting complete android.provider.MediaStore.EXTRA_OUTPUT this solved my bug.

Categories

Resources