I have the following method to download an image from a given URL. When I run the appropriate methods the first time, the file is saved to the sdcard. When I go to re-run these methods, and check if there is a file at the end of the given path, the image is not (i check with file.exists()), and null is returned. Any reason why this activity is going on? The code specifically fails at input = url.openStream().
public class DownloadAndReadImage {
String strURL;
int pos;
Bitmap bitmap = null;
// pass image url and Pos for example i:
DownloadAndReadImage(String url,int position) {
this.strURL = url;
this.pos = position;
}
public String getBitmapLocation() {
return "/sdcard/"+pos+".png";
}
public Bitmap getBitmapImage() {
downloadBitmapImage();
return readBitmapImage();
}
void downloadBitmapImage() {
InputStream input;
try {
URL url = new URL (strURL);
input = url.openStream();
byte[] buffer = new byte[500*1024]; //or 500*1024
OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
try {
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
}
finally {
output.close();
input.close();
buffer = null;
}
}
catch(Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
Bitmap readBitmapImage() {
BitmapFactory.Options bOptions = new BitmapFactory.Options();
bOptions.inTempStorage = new byte[16*1024*1024];
String imageInSD = "/sdcard/"+pos+".png";
bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
boolean exists = new File(imageInSD).exists();
return bitmap;
}
}
This is the call code:
private void saveImage() {
DownloadAndReadImage dImage = new DownloadAndReadImage(imageAddress, count);
image = dImage.getBitmapImage();
}
Here is my Async code
public void submitFile() {
if(URLUtil.isValidUrl(imageAddress)) {
new AsyncTask<Void, Void, Boolean>() {
protected Boolean doInBackground(Void... voids) {
boolean img = false;
boolean youtube = false;
HttpURLConnection connection = null;
try {
URL url = new URL(imageAddress);
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String contentType = connection.getHeaderField("Content-Type");
img = contentType.startsWith("image/");
if(img)
media = "image";
if (!img) {
// Check host of url if youtube exists
Uri uri = Uri.parse(imageAddress);
if ("www.youtube.com".equals(uri.getHost())) {
media = "youtube";
youtube = true;
}
}
return img || youtube;
}
protected void onPostExecute(Boolean valid) {
if (valid) {
Picasso.with(Demo.this).load(imageAddress).into(imagePreview);
saveImage();
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //refreshes system to show saved file
submitted = true;
submit_but.setText("Encrypt");
}
}
}.execute();
}
}
I am using android studio. Thank you for your assistance.