I want to save multiple images in a folder on sdcard but when saving new image, previous ones gets overwritten. How can I save multiple images in my folder?
File mydirectory = new File(Environment.getExternalStorageDirectory() + "/AppFolder");
if(!mydirectory.exists()){
mydirectory.mkdir();
}
if(mydirectory.exists()){
try {
File root = new File(Environment.getExternalStorageDirectory() +"/AppFolder");
File sdImageMainDirectory = new File(root , "pic.png");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error occured. Please try again later.",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void startCameraActivity() {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 101);
}
You are saving each file with name as pic.png.
You need to change the file name each time.
Edit:
In addition to answer by #David Xu, if you want to have unique name each time, you can just append a unix timestamp at the end of the file name as follows
dImageMainDirectory = new File(root, "pic_" + (System.currentTimeMillis() / 1000L) + ".png");
change
File sdImageMainDirectory = new File(root , "pic.png");
to
File sdImageMainDirectory = null;
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
Every file you create has the same name. Here's a quick and dirty solution:
try{
File root = new File(Environment.getExternalStorageDirectory() +"/AppFolder");
int i = 0;
File sdImageMainDirectory = new File(root , "pic.png");
while(sdImageMainDirectory.exists()){
i++
sdImageMainDirectory = new File(root , "pic" +i+ ".png");
}
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {
You are using the same name for every picture which is why it is getting overwritten
File sdImageMainDirectory = new File(root , "pic.png");
you are naming them all pic.png
Try developing a naming convention like pic1.png, pic2.png or you can save the png as the name of the current timestamp like this:
//get timestamp into string
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String timeStamp = df.format(today);
File sdImageMainDirectory = new File(root , timeStamp + ".png");
Related
using camera2 api i m save file like this
if (Build.VERSION.SDK_INT <=Build.VERSION_CODES.P){
final String folderPath = Environment.getExternalStorageDirectory() + "/Pikpap/";
file1 = new File(folderPath);
} else{
file1 = new File( CameraFragment.view.getContext().getExternalFilesDir()+ "/Pikpap/");
}
if (!file1.exists()) {
file1.mkdirs();
}
String fullName = file1.getAbsolutePath() + "Pikpap" + currentTime+name + ".jpg";
File file = new File(fullName);
but some time file not save and image blank set on image view
this issue created on all devices
I have this code here that saves bitmaps of images as a GIF file called test, but everytime the user saves it as test.gif so its constantly overwriting.
What are some ways to avoid overweriting and generate a new filename everytime programmatically?
if(imagesPathList !=null){
if(imagesPathList.size()>1) {
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "test.gif");
try{
FileOutputStream f = new FileOutputStream(file);
f.write(generateGIF(list));
} catch(Exception e) {
e.printStackTrace();
}
A quick and dirty solution is to put the system time in the filename:
File file = new File(dir, "test_" + System.currentTimeMillis() +".gif");
As long as that method isn't executed at the exact same millisecond, you won't have duplicates.
You can use java.io.File.createTempFile("test", ".gif", dir)
This creates unique filename but they might get significantly long after some time.
Alternatively you can create a method that creates unique filesnames yourself:
private File createNewDestFile(File path, String prefix, String suffix) {
File ret = new File(path, prefix + suffix);
int counter = 0;
while (ret.exists()) {
counter++;
ret = new File(path, prefix + "_" + counter + suffix);
}
return ret;
}
Instead of
File file = new File(dir, "test.gif");
you call
File file = createNewDestFile(dir, "test", ".gif");
This is not thread safe. For that you need a more sophisticated method (e.g. synchronize it and create a FileOutputStream instead of a File which is creating the file already before another call checks of the method checks its existence).
I know with Kit Kat you can only write to your applications package specific directory on SD Cards. I was however under the impression you could still copy files from an SD card to local storage with the:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am simply testing if I can copy one file. If I am able to do that I will add the code to search the entire SD card DCIM folder. For now I have the following code (please forgive the messiness of the code, I have written C# and vb.net but java is still very new to me):
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
String CamPath = projDir + File.separator + tv2.getText();
File projDir2 = new File(CamPath);
if (!projDir2.exists())
projDir2.mkdirs();
File LocalBuck = new File(projDir2 + File.separator );
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
File directory = new File(directory1 + "/100SDCIM");
File Buckfile = new File(directory, "/BigBuck.jpg");
try {
exportFile(Buckfile, LocalBuck);
} catch (IOException e) {
e.printStackTrace();
}
Here is my code for the export function/application:
private File exportFile(File src, File dst) throws IOException {
//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//Straight to Error Handler
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
return expFile;
}
Here is what my emulator looks like:
Looking for: Debug of SD Location
Should Find It?: EmulatorShowingSd
Question: Am I even able to copy a file from the SD card to local storage after KitKat; if so what is wrong in the code causing the exception to be thrown when it tries to access the SD card file?
This question already has answers here:
Backup and restore SQLite database to sdcard
(3 answers)
Closed 8 years ago.
in my app I need get a backup of my database,
but after I'll need restore it again,
i have read somethings, but i do not sure if this is necessary to have a rooted device,
i need backup/restore the all data in non root devices, is it possible?
my first idea was creating a txt file for write the select, and later insert it again.
but i believe this is much "problem" then i don't know if this is possible copy the database and paste in sd card for backup, and copy from sd card and paste in path of database for restore for non root devices.
Here is some code to make it work
private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "<package name>"
+ "//databases//" + "<database name>";
String backupDBPath = "<backup db filename>"; // From SD directory.
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Import Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Import Failed!", Toast.LENGTH_SHORT)
.show();
}
}
private void exportDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "<package name>"
+ "//databases//" + "<db name>";
String backupDBPath = "<destination>";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Backup Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Backup Failed!", Toast.LENGTH_SHORT)
.show();
}
}
I am new to android and programming. I am using the android touchpaint api, and using the following code to save a drawing, but obviously saving is useless without being able to open the file.
I was wondering if anyone could help me with some code for it.
// Function saves image to file
public String save(Bitmap mBitmap, boolean showMsg) {
String filename;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename = sdf.format(date);
try {
String path = Environment.getExternalStorageDirectory().toString() + "/modTouchPaint/";
File file1 = new File(path);
file1.mkdirs();
OutputStream fOut = null;
File file = new File(path, filename + ".jpg");
fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
if (showMsg)
Toast.makeText(this, "Picture saved to " + path + filename + ".jpg", 9000).show();
return path + filename + ".jpg";
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Please make sure that SD card is installed", 5000).show();
return null;
}
}
Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);
See the documentation for more information.