Android how to create a new file for each download? - android

I am creating an app where every time press the download button it's create a pdf file in my storage.My problem is newly created file overwrites the existing file with same file name.I need to download with new filename.What i am trying
dirpath =
android.os.Environment.getExternalStorageDirectory().toString();
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");}
This above lines of program create files but i need to open the last download file
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf"));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
These above lines of code generate an error.
Error:File no longer exist,the file maybe deleted or changed or
removed by another program
1.create a new file and prevent overwiting whenever i click the button
2.open the last downloaded file
I am new to Android and little confused about that and kindly need some help from you guys.

You call Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf")); for open file, so why you added /NewPDF.pdf because its already in your file. just remove it.
Replace this line
Uri uri = Uri.fromFile(new File( file,"/NewPDF.pdf"));
to
Uri uri = Uri.fromFile(new File( file));

You are assigning the same name to every file you create. Try giving a unique name like this:
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
the randomUUIDString will be your unique string for the pdf files. Also, store these strings in a SQLite db if you wish to use them.

The path you have entered in intent not matching with the created file path.
Try this.
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
String lastFilePath = null;
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");}
lastFilePath = file.getAbsolutePath();
Then you can open the file like this.
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(lastFilePath));
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Hope it helps:)

Replace if with while and display Intent:
dirpath = android.os.Environment.getExternalStorageDirectory().toString();
int increase = 0;
file = new File(dirpath+"/NewPDF.pdf");
while(file.exists()) {
increase++;
file = new File(dirpath + "/NewPDF" +increase+".pdf");
}
file.createNewFile();
... store data in file here ...
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

Use Time stamp instead of Counter, so that you can create a new file every time.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);
Date timeStamp = new Date();
dirpath =
android.os.Environment.getExternalStorageDirectory().toString();
// int increase=0;
file = new File(dirpath+"/NewPDF.pdf");
if(file.exists()){
increase++;
file = new File(dirpath + "/NewPDF" +formatter.format(timeStamp )+".pdf");}

Related

I'm trying to share a file from my android app, but iIm getting an error like file not supported or unknown file

I'm trying to share a file from my android app, but I'm getting an error like file not supported or unknown file.
CommonMethods commonMethods = new CommonMethods();
String internalFile = commonMethods.getDate();
String sharepath = Environment.getExternalStorageDirectory() + "/My Records/" + internalFile + "/";
Uri urii = Uri.parse(sharepath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM,urii);
startActivity(Intent.createChooser(share,"Share Sound File"));

Android camera intent should not allow to save the image to gallery and store it in specified path

when i use this code ->
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
I am able to save the image to specified path but it is also saving to the gallery. I dont want to save the image to gallery. Please help here.
Thanks in advance for your valuable time.
try this
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFilename());
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
method to return file name that you can specify whre you want to save
public String getFilename() {
File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
if (!file.exists()) {
file.mkdirs();
}
String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
return uriSting;
}
Capture Image using below Intent -
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// create a file to save the image
File MyDir = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir");
if (!MyDir.exists()){
MyDir.mkdirs()
}
File fileUri = new File(MyDir.getAbsolutePath() + File.separator + "IMG_"+ timeStamp + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
The gallery app scans the folders for Media contents and populates them in gallery.
If you wish not to display your captured images in gallery follow below methods-
Creating A .Nomedia File
Adding A Dot Prefix
I faced the same problem and implemented several workarounds similar to this one.
I tried also to keep the file hidden adding the . prefix to the filname and to put a .nomedia file (see MediaStore.MEDIA_IGNORE_FILENAME) within the folder where I stored the images but in some cases, calling the camera app via intent as usual
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
Uri fileUri = FileProvider.getUriForFile(getContext(), getString(R.string.file_provider_authority), file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
} else {
showToastMessage(getString(R.string.no_camera_activity), Toast.LENGTH_LONG);
}
depending on the device and the camera app, this latter might store the picture also within the gallery (usually saving a file with a timestamp as the filename) even if you are providing an Uri associated to a file you are storing within your application private partition.
So I found that the most reliable way of doing what I needed was to control the camera directly by your own or to adopt cwac-cam2 library provided by CommonsWare within YourActivity in this way (note the commented .updateMediaStore() line)
Uri fileUri = FileProvider.getUriForFile(getContext(), getString(R.string.file_provider_authority), file);
CameraActivity.IntentBuilder builder = new CameraActivity.IntentBuilder(this); // this refers to the activity instance
Intent intent = builder
.skipConfirm()
.facing(Facing.BACK)
.to(fileUri)
//.updateMediaStore() // uncomment only if you want to update MediaStore
.flashMode(FlashMode.AUTO)
.build();
startActivityForResult(intent, CAMERA_REQUEST_CODE);

Android filepath photo ends up with file:///

I'm trying to get the right filepath to an image I'm taking with the camera. I get the right filepath but it ends up with
file:///storage/emulated/0/Pictures/picture.jpg
when i want it to end up as
storage/emulated/0/Pictures/picture.jpg Any clues on how ti fix this?
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), pictureName);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pictureDirectory));
imageToUploadUri = Uri.fromFile(pictureDirectory);
//this ends up as file:///
filepath = imageToUploadUri.toString();
Try:
filepath = imageToUploadUri.getPath();
or
File f = new File(imageToUploadUri.getPath());
filepath = f.getAbsolutePath();

How to save captured photo in application directory in Android

Hello I want to save captured photo in application directory where SQLite etc reside. I don't want to make any folder and any hidden file in the SD Card. How this can be save the captured photo in application directory.
I am trying this below but it is saving in the SD card that is hidden file but I don't want this approach.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String capturedPhotoName = "." + System.currentTimeMillis() + ".png";
File photo = new File(Environment.getExternalStorageDirectory(),
capturedPhotoName);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERA_INTENT_REQUEST);
Thanks in advance !
Try this method to save captured image in application storage
public Uri setImageUri() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File file = new File(directory,System.currentTimeMillis() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
Image will store at this location
/data/data/com.your.packagename/app_data/imageDir
get URI from onActivityResult() and convert it into bytes store bytes in Database.
byte[] UserPic = null;
UserPic = Base64.decode(result.getData(), 0);
save userPic in DataBase

What's the path in jblough / Android-Pdf-Viewer-Library?

Looking at the following website:
https://github.com/jblough/Android-Pdf-Viewer-Library
He's listed the following code:
Intent intent = new Intent(this, YourPdfViewerActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, "PATH TO PDF GOES HERE");
startActivity(intent);
What will that path be and where I be placing this PDF file?
I have placed a test PDF file in assests folder, res/raw. Pushed a file from the ddms in data/data/project, and in libs folder as well. I tried the following but I am still getting file not found:
String path = Environment.getExternalStorageDirectory().getPath();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "test.pdf";
String path = "android.resource://com.example.test3/raw/test.pdf";
String path = "file:///android_assets/test.pdf";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.pdf";
final File cacheDir = context.getDir("cache", 0);
if(!cacheDir.exists()) cacheDir.mkdirs();
final File fileContent = new File(cacheDir, "test1.pdf");
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test1.pdf";
path = fileContent.getPath();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
Ran it first time, it created that folder, then I placed the file in that folder and ran it again and it was able to find the file. Placed the file from the ddms. Answered by Selvin.
The easiest, which worked for me:
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "pdfName.pdf");
String path = f.getPath();
Intent intent = new Intent(this, BulaActivity.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);

Categories

Resources