Main navigation

Android Retrofit 2.0 Tutorial: Retrofit Android Example of How to download image from URL and display it on Android device screen.

adsense

Pre-requisites:

1) Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
2) A real time android device (Smartphone or Tablet) configured with Android Studio. .
3) A basic knowledge of Android lifecycle and different classes & functions used in Android Studio.
4) Go through our previous post of Example of Retrofit 2.0 capturing JSON Array and JSON Object from URL

File Handling Method

In this method we will use FileInputStream and FileOutputStream methods to download image. Let’s see how it is done. I hope you have already gone through our previous tutorial of Retrofit 2.0 capturing JSON Array and JSON Object from URL . That will be reused here.

Note: We don’t need any POJO class here. We will simply use ResponseBody to download Image.

Creating a New Project and Adding Android Retrofit 2.0

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have left Activity Name as MainActivity.
  5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.
  6. To add Android Retrofit 2.0 to your project add the following dependency in your App’s build.gradle file.
  7. compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.google.code.gson:gson:1.7.2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp:okhttp:2.4.0'
    

    Add Internet Permission

    Add the following permission to your AndroidManifest.xml file

    AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />
    

    Interface Declaration:

    Make a new interfaces with name RetrofitImageAPI at the path:
    …/AndroidRetrofit2.0ImageDownload/app/src/main/java/com/androidtutorialpoint/androidretrofit20imagedownload/

    RetrofitImageAPI.java

    package com.androidtutorialpoint.androidretrofit20imagedownload;
    
    import com.squareup.okhttp.ResponseBody;
    
    import retrofit.Call;
    import retrofit.http.GET;
    
    public interface RetrofitImageAPI {
        @GET("api/RetrofitAndroidImageResponse")
        Call<ResponseBody> getImageDetails();
    }
    
    

    In the above code, we are using ResponseBody as return type. getImageDetails will be called inside MainActivity.java to get thedetails of image. @GET is used to call server (corresponding to URL). It is predefined part of android retrofit library. Only end part of URL will be added here.

    Capturing Image using Android Retrofit 2.0

    Now comes the most important part i.e. Downloading image and showing it on device screen. We will make function named getRetrofitImage() in MainActivity.java to get the response from server and DownloadImage() to download and show it on device screen. getRetrofitImage() will be called when user clicks on switch.

    getRetrofitImage()

    void getRetrofitImage() {
    
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    
            RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
    
            Call<ResponseBody> call = service.getImageDetails();
    
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
    
                    try {
    
                        Log.d("onResponse", "Response came from server");
    
                        boolean FileDownloaded = DownloadImage(response.body());
    
                        Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
    
                    } catch (Exception e) {
                        Log.d("onResponse", "There is an error");
                        e.printStackTrace();
                    }
    
                }
    
                @Override
                public void onFailure(Throwable t) {
                    Log.d("onFailure", t.toString());
                }
            });
        }
    
    

    In the above code we build Retrofit using Retrofit.Builder() and converted JSON data into accessible data object using GsonConverterFactory. You can read more about GSON. After this we passed our interface RetrofitImageAPI to the retrofit to get details of the Image. Now comes the next part i.e. Executing call and Printing data on device screen.
    Calls may be executed synchronously with execute(), or asynchronously with enqueue(). enqueue() will Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response. If response comes then onResponse will be automatically called. If response doesn’t come out then onFailure will be called and reason of failure will be printed.

    If response comes out then DownloadImage will be called to take care of file handling part.

    DownloadImage()

    private boolean DownloadImage(ResponseBody body) {
    
            try {
                Log.d("DownloadImage", "Reading and writing file");
                InputStream in = null;
                FileOutputStream out = null;
    
                try {
                    in = body.byteStream();
                    out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg");
                    int c;
    
                    while ((c = in.read()) != -1) {
                        out.write(c);
                    }
                }
                catch (IOException e) {
                    Log.d("DownloadImage",e.toString());
                    return false;
                }
                finally {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                }
    
                int width, height;
                ImageView image = (ImageView) findViewById(R.id.imageViewId);
                Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg");
                width = 2*bMap.getWidth();
                height = 6*bMap.getHeight();
                Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
                image.setImageBitmap(bMap2);
    
                return true;
    
            } catch (IOException e) {
                Log.d("DownloadImage",e.toString());
                return false;
            }
        }
    

    I would suggest you to read about Input and Output Stream handling. It is very simple. In the above code, we are storing stream of data in the InputStream in. Handle for OutputStream out is created through new FileOutputStream() where path of the file is specified by getExternalFilesDir(null) + File.separator + and name of file as AndroidTutorialPoint.jpg. Now we are reading stream of data using in.read() and writing it on the specified path using out.write(c). Finally after writing full data we are closing each of the files. So our Download portion is complete.

    Now we have to display image on our Android device. This will be done through BitmapFactory. As you could see in above code, we are decoding path of file using BitmapFactory.decodeFile (This path is same as the path where we downloaded file) and then changing its width and heigth according to requirement of our Android device. Finally, image is displayed using image.setImageBitmap.

    Layout

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="https://schemas.android.com/apk/res/android"
        xmlns:app="https://schemas.android.com/apk/res-auto"
        xmlns:tools="https://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.androidtutorialpoint.androidretrofit20imagedownload.MainActivity"
        tools:showIn="@layout/activity_main">
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Retrofit Android Image"
            android:layout_marginTop="150dp"
            android:layout_centerHorizontal="true"
            android:id="@+id/RetrofitImage" />
    
        <ImageView
            android:id="@+id/imageViewId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>
    

    Here we have added a button to start downloading of Image from server. If you click on Android Retrofit Image then image will be shown on device screen as shown below:

    AndroidRetrofitImageTutorial



    What’s Next?

    With the knowledge of how to use Retrofit 2.0 in Android Applications, you can experiment with different API’s available on the internet, parse them and create beautiful android applications. You can even try to download zip files. You can’t download large chunk of data using Android Retrofit, you have to use DownloadManager for it. You can refer our tutorial on Android Download Manager .

    Moreover wanna a work on a project of Retrofit ?? Refer Google Maps Nearby Places API using Retrofit Android.

    Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

    You can Download this full code by clicking below:

    Android Tutorial Point Download Now



Reader Interactions

Comments

  1. Thanks for the tutorial 🙂

    One assumption that’s made in this tutorial is that we already know the image type.
    What if we don’t know (image is downloaded as a binary)? Is it safe to simply assume the image type or force it as a jpg (for example)?

Leave a Reply

Advertisment ad adsense adlogger