Search code examples
androidpicasso

Trying to save Image in External Storage with Picasso


I am trying to fetch image from URL for display and also wants to store in an external storage of our phone. I am not getting error but also the image is not been saving in disk, Why ? I am not getting. May be it's very small problem but I am very newbie to making android apps, so Please give me a suggestions what should I need to do . I am calling Picasso twice like this ....

Picasso.with(this).load(currentUrl)
//.error(R.drawable.error_detail)
.into(imageView, new EmptyCallback() {
    @Override public void onSuccess() {
        progressBar.setVisibility(View.GONE);
    }
    @Override
    public void onError() {
        progressBar.setVisibility(View.GONE);
    }
});

Picasso.with(this)
        .load(currentUrl)
        .into(target);

target Class is like this ---->

private Target target = new Target() {

@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() +"/image.jpg");
            try
            {
                file.createNewFile();
                FileOutputStream ostream = new FileOutputStream(file);
                bitmap.compress(CompressFormat.JPEG, 75, ostream);
                ostream.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
    if (placeHolderDrawable != null) {
    }
}
};

Solution

  • Ask for run time permission

    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
    

    Check document https://developer.android.com/training/permissions/requesting.html