Retrofit 2 download image and save to folder
<p>I need to download image from server and save it to folder, so I am using Retrofit 2.</p>

<p>Problem is that saved images is empty when I look for it in folder and I tried to debug and saw that Bitmap is null. </p>

<p>I do not get why, here is my code:</p>

<pre><code>@GET("images/{userId}/{imageName}")
@Streaming
Call&lt;ResponseBody&gt; downloadImage(@Path("userId") String userId, @Path("imageName") String imageName);
</code></pre>

<p><strong>Download image code:</strong> </p>

<pre><code> private void downloadImage(final int position) {
    String url = "htttp://myserver.com/";
        retrofitImage = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    imageApi = retrofitImage.create(BlastApiService.class);

    String userId = feedList.get(position).getUserId();
    String fileName = feedList.get(position).getFile();

    Call&lt;ResponseBody&gt; imageCall = imageApi.downloadImage(userId, fileName );
    imageCall.enqueue(new Callback&lt;ResponseBody&gt;() {
        @Override
        public void onResponse(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response) {
            if(response.isSuccess()){
                String fileName = feedList.get(position).getFile();
                InputStream is = response.body().byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                saveImage1(bitmap, fileName);
            } else{
                try {
                    Log.d("TAG", "response error: "+response.errorBody().string().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call&lt;ResponseBody&gt; call, Throwable t) {
            Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
        }
    });

}
</code></pre>

<p>Here is method to <strong>save image</strong>.</p>

<pre><code> private void saveImage1(Bitmap imageToSave, String fileName) {
    // get the path to sdcard
    File sdcard = Environment.getExternalStorageDirectory();
    // to this path add a new directory path
    File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
    // create this directory if not already created
    dir.mkdir();
    // create the file in which we will write the contents
    File file = new File(dir, fileName);
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        counter++;
       // if (counter &lt; feedList.size()) {
            //downloadImage(counter);
        //} else {
            setImage();
        //}
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code></pre>