nEwDeV nEwDeV - 4 months ago 15
Android Question

I want to save image and if image is already downloaded then its give direct path

I download image from server and save it in external storage but the problem is, it saved only one image but I want that user can download all images and save them in external storage and when user clicked listview item, then if image is already downloaded then it give image path but if image is not download, first download it and then give imagepath.

my code is..

class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(context);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="Name"+".png";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
PATH = Environment.getExternalStorageDirectory()+ "/pictures/myApp/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();

}
}
protected void onPostExecute(long result) {
super.onPostExecute(result);
String imagePath =Environment.getExternalStorageDirectory() + "/Pictures/myApp/"+targetFileName;
File f=new File(imagePath);
Uri uri = Uri.fromFile(f);
Intent i = new Intent(android.content.Intent.ACTION_SEND);
i.setType("image/*");
i.putExtra(android.content.Intent.EXTRA_TEXT, "This is tesing");
i.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(i, "Share via"));

}
}


its work fine but it save only one image in sdcard.

Answer

This is because you save the file will same name always. It over writes your previous file.

Try changing this

String targetFileName="Name"+".png";//Change name and subname

To

String targetFileName="Image_"+System.currentTimeMillis()+".png";