Click here to Skip to main content
14,579,188 members
Rate this:
Please Sign up or sign in to vote.
See more:
There is no problem in downloading 1 image but when I try downloading another image, it overwrites the previous image.
In short I can download only 1 image.

My code is given below.Tell me the correct code so that multiple image can be downloaded.


FileOutputStream outputStream = null;

File myDir = Environment.getExternalStorageDirectory();
File fileDir = new File(myDir.getAbsolutePath() + "/Wallpaper");
fileDir.mkdir();

String fileName = String.format("wallpaper.jpg" ,System.currentTimeMillis());
File outFile = new File(fileDir,fileName);
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
context.sendBroadcast(intent);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

What I have tried:

I don't know what else to do with this code.
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

That's because you specify the filename absolutely:
String fileName = String.format("wallpaper.jpg" ,System.currentTimeMillis());
File outFile = new File(fileDir,fileName);

Unless you specifically change that file name, every file you download will go to the same file, overwriting all the others.

You might want to think about how you want to store these: different folders for each day or week maybe, date and time stamped filenames, incrementing numbers, ... there are a lot of options you can pick from.
   
Comments
Developer 101 24-Jun-20 0:40am
   
thanks for your answer....can you give me the code for time stamped filenames.
OriginalGriff 24-Jun-20 1:03am
   
You are kidding, right?
You username implies you are a developer: just get the current DateTime, convert it to a string ("yyyyMMDDHHmmss.sss" is a good idea as it sorts well) and use that.
One line of code in most languages ...
Rate this:
Please Sign up or sign in to vote.

Solution 2

String fileName = String.format("wallpaper.jpg" ,System.currentTimeMillis());

You forgot to add the format specification for the time value, it should be:
String fileName = String.format("wallpaper_%d.jpg" ,System.currentTimeMillis());

Although the milliseconds value is somewhat long so you may wish to shorten it.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100