I have recyclerview and in every recyclerview item, I have images. I also have a download button in every recyclerview item.
If the user will click on download button, images of that recyclerview item will download and store it.
Till here it works fine, now the issue is that, if a user is downloading an image of the first product, and the user will download another image for the next product, images in the gallery is being replaced.
public class DownloadImage extends AsyncTask<String, Void, Void> {
private Context context;
private DownloadImage(Context context) {
this.context = context;
}
@Override
protected Void doInBackground(String... params) {
int ii = 0;
for (int k=0;k<resellerProductLists.get(imgpos).getProductImageDtoList().size();k++) {
//Toast.makeText(context,resellerProductLists.get(0).getProductImageDtoList().get(k).getImageUrl(),Toast.LENGTH_SHORT).show();
Log.e("Image",resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageUrl());
ii++;
String img = "IMG-";
String mPath = Environment.getExternalStorageDirectory().toString() + "/Temp/" + img + ii + ".jpg";
File Directory = new File(Environment.getExternalStorageDirectory().toString() + "/Temp");
Directory.mkdirs();
try {
File file = Glide.with(context)
.load(resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageUrl())
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
File imageFile = new File(mPath);
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(new FileOutputStream(mPath));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (InterruptedException | ExecutionException | IOException e) {
hideLoading();
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void res) {
super.onPostExecute(res);
//prodImageUri1.addAll(prodImageUri);
// hideLoading();
Toast.makeText(context,"Download Complete Successfully", Toast.LENGTH_SHORT).show();
}
}
Can anyone assist me with this problem?
Image in the gallery is being replaced because both images have same name. This is because your variable 'ii' is initiliazed inside the 'doInBackgroud()' function hence name of image always become "../temp/IMG-1.jpg". To prevent replacing of old Images you can do either of the Following :
int ii=0
with String ii = System.currentTimeMillis().toString()
, This will gurantee that ii is unique every time .