I\'m setting an ImageView using setImageBitmap with an external image url. I would like to save the image so it can be used later on even if there is no interne
May be its will help someone like me one day
new SaveImage().execute(mViewPager.getCurrentItem());//calling function
private void saveImage(int currentItem) {
String stringUrl = Site.BASE_URL + "socialengine/" + allImages.get(currentItem).getMaster();
Utils.debugger(TAG, stringUrl);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(stringUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String fileName = stringUrl.substring(stringUrl.lastIndexOf('/') + 1, stringUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
File imgFile = new File(sdCardRoot, "IMG" + System.currentTimeMillis() / 100 + fileName);
if (!sdCardRoot.exists()) {
imgFile.createNewFile();
}
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
FileOutputStream outPut = new FileOutputStream(imgFile);
int downloadedSize = 0;
byte[] buffer = new byte[2024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
outPut.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Utils.debugger("Progress:", "downloadedSize:" + Math.abs(downloadedSize*100/totalSize));
}
outPut.close();
//if (downloadedSize == totalSize);
//Toast.makeText(context, "Downloaded" + imgFile.getPath(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private class SaveImage extends AsyncTask {
@Override
protected String doInBackground(Integer... strings) {
saveImage(strings[0]);
return "saved";
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(context, "" + s, Toast.LENGTH_SHORT).show();
}
}