How to save a picture and access it on a PC? - java

I'm following the Google Camera Tutorial for an Android application. At this moment, I'm able to take a picture, save it, show the path and show the bitmap into an ImageView.
Here is an exemple of the logcat when I ask for the absolute path of a picture I just took :
D/PATH:: /storage/emulated/0/Pictures/JPEG_20160210_140144_217642556.jpg
Now, I would like to transfer it on a PC via USB. When I broswe into the device storage, I can see the public folder Picturethat I called earlier in my code with the variable Environment.DIRECTORY_PICTURES. However, there is nothing in this folder.
Screenshot of my device's folders
I can't insert a SD Card in my device to test. Also, I don't want to put the pictures into cache directory for preventing to be deleted.
Here is my permissions in Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
When the user click on the camera buttons :
dispatchTakePictureIntent();
[...]
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
This is method creating the file
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Log.d("PATH:", image.getAbsolutePath());
return image;
}
I guess I misunderstood something about the External Storage. Can someone explain me why I can't save a picture and access it on a PC ? Thank you !
-- EDIT --
After reading an answer below, I tried to get the file in OnActivityResult and to save it with Java IO. Unfortunately, there is no file in Pictures folder when I look with Explorer.
if (requestCode == REQUEST_TAKE_PHOTO) {
Log.d("AFTER", absolutePath);
// Bitmap bitmap = BitmapFactory.decodeFile(absolutePath);
// imageTest.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 2100, 3100, false));
moveFile(absolutePath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
}
private void moveFile(String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}
in = new FileInputStream(inputFile);
out = new FileOutputStream(outputPath + imageFileName + ".jpg");
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file
out.flush();
out.close();
out = null;
// delete the original file
new File(inputFile).delete();
}

You're currently saving the file as a temporary file, so it won't persist on disk after the application lifecycle. Use something like:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory() + [filename])
And then create a FileOutputStream to write to it.
FileOutStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

To solve my problem, I had to write the file into the application's data folder and to user the MediaScannerConnection. I've put a .txt file for testing, but after it works you can put any other file.
I'll share the solution for those who have a similar problem :
try
{
// Creates a trace file in the primary external storage space of the
// current application.
// If the file does not exists, it is created.
File traceFile = new File(((Context)this).getExternalFilesDir(null), "TraceFile.txt");
if (!traceFile.exists())
traceFile.createNewFile();
// Adds a line to the trace file
BufferedWriter writer = new BufferedWriter(new FileWriter(traceFile, true /*append*/));
writer.write("This is a test trace file.");
writer.close();
// Refresh the data so it can seen when the device is plugged in a
// computer. You may have to unplug and replug the device to see the
// latest changes. This is not necessary if the user should not modify
// the files.
MediaScannerConnection.scanFile((Context)(this),
new String[] { traceFile.toString() },
null,
null);
}
catch (IOException e)
{
Log.d("FileTest", "Unable to write to the TraceFile.txt file.");
}

Related

Cannot open pdf file that was generated from an InputStream

I have an API that provides me with InputStream of a pdf file. And my objective is to allow user to view this file with another pdf viewer application.
In order to acheive this, I copied the InputStream to a pdf file that has been created programmatically. Then I tried to open that pdf file.
However, I'm not able to open the pdf file through my application or file explorer. Drive PDF viewer tells in toast that it cannot open the pdf file, Adobe Acrobat tells that the pdf file cannot be accessed, and Mi PDF reader tells that the pdf is in invalid format.
Here's the code inside onResponse() of OkHttpClient's call:
if (response.isSuccessful()) {
InputStream inputStream = responseBody.byteStream();
runOnUiThread(new Runnable() {
#Override
public void run() {
File file = null;
try {
file = MyFileUtils.createPdfFile(PdfViewActivity.this);
} catch (IOException e) {
e.printStackTrace();
}
MyFileUtils.copyInputStreamToFile(inputStream, file);
String pdfFilePath = file.getAbsolutePath();
openPdf(pdfFilePath);
}
});
}
Here's the method responsible for opening pdf:
private void openPdf(String pdfFilePath) {
Intent pdfViewIntent = new Intent(Intent.ACTION_VIEW);
pdfViewIntent.setDataAndType(Uri.parse(pdfFilePath), "application/pdf");
Intent chooser = Intent.createChooser(pdfViewIntent, "Open this note with");
startActivity(chooser);
finish();
}
I created the pdf using MyFileUtils.createPdfFile() method. Here's how I implemented it:
public static File createPdfFile(Activity associatedActivity) throws IOException {
String timeStamp = new SimpleDateFormat("HHmmss").format(new Date());
String pdfFileName = "PDF_" + timeStamp + "_";
File storageDir = associatedActivity.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
Log.d(TAG, "createPdfFile: storageDir: " + storageDir.getAbsolutePath());
return File.createTempFile(
pdfFileName, /* prefix */
".pdf", /* suffix */
storageDir /* directory */
);
}
I copied the InputStream to that file using the following method in MyFileUtils class:
// Copy an InputStream to a File.
public static void copyInputStreamToFile(InputStream in, File file) {
OutputStream out = null;
try {
out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Ensure that the InputStreams are closed even if there's an exception.
try {
if (out != null) {
out.close();
}
// If you want to close the "in" InputStream yourself then remove this
// from here but ensure that you close it yourself eventually.
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've implemented the provider in the following way:
AndroidManifest.xml :
<application>
...
...
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.xyz.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
file_paths.xml :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
<external-files-path name="my_documents" path="Documents" />
</paths>
NOTE:
The application has necessary read-write permissions. I've tested it programmatically. I'm not including those codes here because it might not be relevant.
The absolute path of the created pdf file is something like this: /storage/emulated/0/Android/data/<package name>/files/Documents/PDF_164257_4832620770047519807.pdf
You need to download on device download directory.
Your directory is not visible to other's application that's by its not opening.
Only your application can use this directory.
Not able to comment due to less reputation
I am not sure if this helps but I see that the file you copy the InputStream into seems not be closed before you call openPdf(pdfFilePath); which means the pdf viewers get trouble opening it either because it is blocked or not all content has been written into the file.

How can i share apk file in my app (send app itself)

I am trying to use this code to send my application apk file to another device:
public static void sendAppItself(Activity paramActivity) throws IOException {
PackageManager pm = paramActivity.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(paramActivity.getPackageName(),
PackageManager.GET_META_DATA);
Intent sendBt = new Intent(Intent.ACTION_SEND);
sendBt.setType("*/*");
sendBt.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + appInfo.publicSourceDir));
paramActivity.startActivity(Intent.createChooser(sendBt,
"Share it using"));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
}
This code works very well.
But the name of the apk file shared with this code is base.apk
How can I change it?
Copy the file from the source directory to a new directory.
Rename the file while copying and share the copied file.
Delete the temp file after share is complete.
private void shareApplication() {
ApplicationInfo app = getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
Intent intent = new Intent(Intent.ACTION_SEND);
// MIME of .apk is "application/vnd.android.package-archive".
// but Bluetooth does not accept this. Let's use "*/*" instead.
intent.setType("*/*");
// Append file and send Intent
File originalApk = new File(filePath);
try {
//Make new directory in new location
File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
//If directory doesn't exists create new
if (!tempFile.isDirectory())
if (!tempFile.mkdirs())
return;
//Get application's name and convert to lowercase
tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk");
//If file doesn't exists create new
if (!tempFile.exists()) {
if (!tempFile.createNewFile()) {
return;
}
}
//Copy file to new location
InputStream in = new FileInputStream(originalApk);
OutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
//Open share dialog
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
startActivity(Intent.createChooser(intent, "Share app via"));
} catch (IOException e) {
e.printStackTrace();
}
}
Update: this method does not work anymore and throws exception if you implement it. Since android N, we should use content providers if we want to have access to files in memory(like the apk file). For more information please visit this Guide. Although the whole idea of copying and renaming and sharing the copied version is still valid.
You can use this function, test on api 22 and 27
private void shareApplication() {
ApplicationInfo app = getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
Intent intent = new Intent(Intent.ACTION_SEND);
// MIME of .apk is "application/vnd.android.package-archive".
// but Bluetooth does not accept this. Let's use "*/*" instead.
intent.setType("*/*");
// Append file and send Intent
File originalApk = new File(filePath);
try {
//Make new directory in new location=
File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
//If directory doesn't exists create new
if (!tempFile.isDirectory())
if (!tempFile.mkdirs())
return;
//Get application's name and convert to lowercase
tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk");
//If file doesn't exists create new
if (!tempFile.exists()) {
if (!tempFile.createNewFile()) {
return;
}
}
//Copy file to new location
InputStream in = new FileInputStream(originalApk);
OutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
//Open share dialog
// intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", tempFile);
// intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
startActivity(Intent.createChooser(intent, "Share app via"));
} catch (IOException e) {
e.printStackTrace();
}
}
This only happens because it is saved by base.apk name.
To share it as per your need you have to just copy this file into another directory path and rename it over there. Then use new file to share.
This file path[file:///data/app/com.yourapppackagename/base.apk] in data folder is having only read permissions so you can't rename .apk file over there.
2021 Kotlin way
First we need to set a file provider
In AndroidManifest.xml create a File provider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"
/>
</provider>
If you don't have file_path.xml the create one in res/xml (create xml folder if it doesn't exist)
and in file_path.xml add
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="apk"
path="cache/ExtractedApk/" />
</paths>
Now add the code to share the apk
private fun shareAppAsAPK(context: Context) {
val app: ApplicationInfo = context.applicationInfo
val originalApk = app.publicSourceDir
try {
//Make new directory in new location
var tempFile: File = File(App.instance.getExternalCacheDir().toString() + "/ExtractedApk")
//If directory doesn't exists create new
if (!tempFile.isDirectory) if (!tempFile.mkdirs()) return
//rename apk file to app name
tempFile = File(tempFile.path + "/" + getString(app.labelRes).replace(" ", "") + ".apk")
//If file doesn't exists create new
if (!tempFile.exists()) {
if (!tempFile.createNewFile()) {
return
}
}
//Copy file to new location
val inp: InputStream = FileInputStream(originalApk)
val out: OutputStream = FileOutputStream(tempFile)
val buf = ByteArray(1024)
var len: Int
while (inp.read(buf).also { len = it } > 0) {
out.write(buf, 0, len)
}
inp.close()
out.close()
//Open share dialog
val intent = Intent(Intent.ACTION_SEND)
//MIME type for apk, might not work in bluetooth sahre as it doesn't support apk MIME type
intent.type = "application/vnd.android.package-archive"
intent.putExtra(
Intent.EXTRA_STREAM, FileProvider.getUriForFile(
context, BuildConfig.APPLICATION_ID + ".fileprovider", File(tempFile.path)
)
)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
} catch (e: IOException) {
e.printStackTrace()
}
}
If someone trying to generate apk from fragment they may need to change few lines from #sajad's answer as below
Replace
File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
with
File tempFile = new File(getActivity().getExternalCacheDir() + "/ExtractedApk");
2.while importing BuildConfig for below line
import androidx.multidex.BuildConfig // DO NOT DO THIS!!! , use your app BuildConfig.
and if you're getting below EXCEPTION
Couldn't find meta-data for provider with authority
Look for provider info in manifest file
then look for "provider"s name and authority in your manifest file and if it's androidx.core.content.FileProvider then
Replace
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", tempFile);
With
Uri photoURI = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);

Downloading files from a server and put it to /raw folder

Here is I want to make. I want to make an app, for example it has a button that will download a certain video file and put it on the resource(raw) folder. Is it possible?
Short answer : You can not.
You can not, under any circumstance, write/dump a file to the raw/assets folder in runtime.
What you can do is to download the video and store it into Internal Memory (application reserved storage) or External Memory (usually your SDCard))
For example, you can store media files, for instance a Bitmap to your external storage like this.
private void saveAnImageToExternalMemory(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "yourimagename.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And equally, read an file, in this example an image (which is then loaded to an imageView), from external memory
private void loadImageFromStorage(String path){
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Edit: Additionally, you can store your data into internal memory
Alternatively you can also save the Bitmap to the internal storage in
case the SD card is not available or for whatever other reasons you
may have. Files saved to the internal storage are only accessible by
the application which saved the files. Neither the user nor other
applications can access those files
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = context.openFileOutput("yourimage.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
Check this documentation for more information
Regards,

How to access /data folder of another application through your application?

there is a text file that an application produces, I would like to take that file and read it as strings in my application. How can I achieve that, any help would be grateful. Both applications are my applications so I can get the permissions.
Thank you!
This is possible using the standard android-storage, where all the user's files are stored too:
All you need to do is to access the same file and the same path in both applications, so e.g.:
String fileName = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/myFileNameForBothApplications.txt";
Where myFolderForBothApplications and myFileNameForBothApplications can be replaced by your folder/filename, but this needs to be the same name in both applications.
Environment.getExternalStorageDirectory() returns a File-Object to the common, usable file-directory of the device, the same folder the user can see too.
By calling the getPath() method, a String representing the path to this storage is returned, so you can add your folder/filenames afterwards.
So a full code example would be:
String path = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/";
String pathWithFile = path + "myFileNameForBothApplications.txt";
File dir = new File(path);
if(!dir.exists()) { //If the directory is not created yet
if(!dir.mkdirs()) { //try to create the directories to the given path, the method returns false if the directories could not be created
//Make some error-output here
return;
}
}
File file = new File(pathWithFile);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
//File couldn't be created
return;
}
Afterwards, you can write in the file or read from the file as provided e.g. in this answer.
Note that the file stored like this is visible for the user and my be edited / deleted by the user.
Also note what the JavaDoc for the getExternalStorageDirectory() says:
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
I do not know if this is the best/safest way to fix your problem, but it should work.
You can save the text file from your assets folder to anywhere in the sdcard, then you can read the file from the other application.
This method uses the getExternalFilesDir, that returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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 to read:
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");

java.io.FileNotFoundException when trying to copy a image from Photos app

I'm trying to get a image from android Photos app using the share option that point to my PhotoGetFromGallery activity. Here is the code:
public void copy(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
String sourcePath = getRealPathFromURI(imageUri);
if(isExternalStorageWritable()) {
if (imageUri != null) {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
String destinationImagePath = sd + "/Pictures/MyAppImgFolder/";
File source = new File(data, sourcePath);
String fileName = source.getName();
File destination = new File(sd, destinationImagePath + fileName);
try {
copy(source, destination);
} catch (Exception e) {
Log.e("COPY IMAGE ERROR", e.toString() + ". Destination Path is " + destinationImagePath.toString() + " and Source path is "+ sourcePath);
}
}
}
}
sourcePath string returns the correct image path (ex. /storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg). However, I'm getting the FileNotFoundException because Environment.getDataDirectory() returns /data/storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg.
Here is my log:
E/COPY IMAGE ERRORīš• java.io.FileNotFoundException: /data/storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg: open failed: ENOENT (No such file or directory). Destination Path is /storage/emulated/0/Pictures/MyAppImgFolder/ and Source path is /storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg
Here is my AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
My question is how can I get, if possible, any path of images stored at Photos app or Android Gallery?
You should not be using getDataDirectory - you are already being handed a complete path, starting with "/storage" Use the single argument File() constructor passing only the sourcePath, like this:
File sd = Environment.getExternalStorageDirectory();
String destinationImagePath = sd + "/Pictures/MyAppImgFolder/";
//sourcePath is already a full path name
File source = new File(sourcePath);
//redundant String fileName = source.getName();
File destination = new File(destinationImagePath + sourcePath);
//You are proposing many new subdirectories, so you must create them
destination.getParentFile()makeDirs();
//now you can continue with your copy attempt
I managed to solve the problem. Follows the code that works . Thanks to Chris Stratton for guiding me in this matter.
File sd = Environment.getExternalStorageDirectory();
String destinationImagePath = sd + AppConstant.PHOTO_ALBUM;
File imagePath = new File(destinationImagePath);
File source = new File(sourcePath);
String fileName = source.getName();
File destination = new File(destinationImagePath + fileName);
if (!imagePath.exists()) {
imagePath.mkdirs();
try {
copy(source, destination);
Toast.makeText(getApplicationContext(), "Success! File was copy from " + sourcePath + " to " + destinationImagePath, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("COPY IMAGE ERROR", e.toString());
}
} else if(destination.exists() && !destination.isDirectory()){
Toast.makeText(getApplicationContext(), "Image is already on your image folder", Toast.LENGTH_LONG).show();
}

Categories

Resources