Android Retrofit Images Tutorial

android+retrofit+picasso

MakeInfo

In this tutorial,we are using Retrofit (networking) and Picasso (image loading) library for loading images into a listView .This is an intermediate tutorial.

After introducing Retrofit and why we chose it for Android Rest Calls in my previous article.Now ,we are going to next level,using retrofit and another library ‘Picasso‘ from square to load images.I also hinted about this library in basic tutorial.

Retrofit individually cannot load images so here came this library,but Picasso not only load the image,it will take care of the cache and memory.There is only few lines of code required to load images from external sources in Picasso.

The example project  is added to Github.


Why Picasso ?

There are many image loading libraries available on internet. But Picasso (Square) ,Glide (Bump),Universal-Image-Loader (nostra13) are my favorites. Each has its own advantages and limits.UIL has many features in my experience compared to other,but its not beginner friendly.

I use Picasso in this tutorial because its easy to manage and both libraries(Retrofit) used in this project is from same company (Square) .

Glide is from bumptech and Google also used this for their projects (ioshed).Its really like Picasso esp. the coding style.It will save the images to cache and will load up fast.If your are need to store the images for further uses,then you can definetely use this library.

picvsglide

http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

There is a good comparison i got when googling, Introduction to Glide 

But Glide has bigger size compared to Picasso : 430KB  vs 118 KB .

As i already said Picasso has limited features esp. the transformations compared to UIL. So to add more transformation features,you can use Picasso Transformation . He also had a Glide Transformation library.Try this.

Note : Wisely choose the library for your project.


1) Introduction

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

This is the only introduction i need to give for Picasso. Here,we give the ContextURL and ImageView ,then we successfully loaded the image.Read this introduction part from Square.After reading the introduction part,also read the http://code.tutsplus.com/tutorials/android-sdk-working-with-picasso–cms-22149,they will give a project idea like Introduction,Installation with a simple project,I recommend this to you.

In today’s project , we are using Api from 

For images,we use : http://services.hanselandpetal.com/photos/   + Flower name (from json)

In this Project, We will retrieve list of Flower Name and Images into a listView .

For getting best Json View,Use

for Chrome Users : https://github.com/gildas-lormeau/JSONView-for-Chrome (Also in Store)

for Firefox Usershttp://benhollis.net/software/jsonview/

Download APK

Untitled (1)


 

2) Requirements

For this project we need :

  1. Andriod Studio
  2. Retrofit
  3. Picasso
  4. You must read the Previous Retrofit Basic Tutorial.

3 ) Adding Libraries in Android Studio

 1) Retrofit  :
     compile 'com.squareup.retrofit:retrofit:1.9.0'

or Download JAR file 

2) Picasso  :
compile 'com.squareup.picasso:picasso:2.5.2'

or download JAR file.


4) Create Project

1) Create new Android Project by : File => New Project and fill description and click Next.

2) Fill the minimum SDK for the project, i use 4.0+ (Retrofit  requires Android 2.3+ or Java 6)

3) Select Blank Activity and then fill out the details Activity Name and Layout Name then click Finish.

4) For Gradle : You can add Retrofit and Picasso library by adding it on app =>build.gradle (in project view).

buildgradle file

For Jar : Add jar to app => libs folder and right click on the jar file and click on Add as Library.

5) Also create two packages as network and model.

6) Right Click on network and Click New => Java Class ,then  Name it as api and Kind as Interface.

7) Right Click on Package model and Click New => Java Class,then Name it as Flower and Kind as Class.

8) Right Click on Package and Click New => Java Class,then name it as adapter (this will use for list view adapter).

file structure


5) Android Manifest.xml

1) Add  INTERNET PERMISSION

6) Model Class

Before coding Model Class ,take a look at the json here, 

The result  is JSON Array starting with ‘[‘ and ending with ‘]’ in between we can see the JSON Objects.

If you don’t  know the difference between Json Array and Json Object,i will recommend this.

In order to create model class or pojo , i find that jsonschema2pojo (which i explain in previous tutorial) is not working for me.So, the next method is by using http://jsongen.byingtondesign.com/ which has more features.Click Generate with your link.

jsongen

http://jsongen.byingtondesign.com/

7) api.java

This is Interface we created for network calling. Here,we just need to use annotation.         (“/feeds/flowers.json”) where, “/feeds/flowers.json” is the link after the Base URL. The Code will be :

8) Layout

Before jumping into java code,now we need to design our app layout. In this project, we are loading the images and text in a listview element using ArrayAdapter .

a) activity_main.xml

Our main layout look like this.
Noteandroid:id=”:id/list” 

b) item_file.xml

Next,we need to create a item file which we will inflate into listview element.Here, we need a ImageView for loading images  and TextView for preview the Flower Names.

9) adapter.java

After designing the listview layout  and item layout,now we are using array adapter.If you are new to listview and arrayadapter, please read this article https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.

 Note that, getView() will be called for each item to display.We also created a list with model Flower.

What happend in getView() :

1) Layoutinflater will inflate the item_file layout.

2) Then, we get position from the list.

3) Initialize the textView and we print the flower name.

4) Initialize the ImageView .

5) Now, we use Picasso for loading the image from the url. we also re-size the image .

10)  RestAdapter Code

I already discuss that ,json array is the result here.So, we need to store the each elements(jsonObject) into a list with model Flower .The Base URL is :  http://services.hanselandpetal.com After calling the getData function from rest adapter, 1) On Success (), we get the result into flowerList  and then, we create  new adapter object which will display the list into item_file.xml 2) On failure(), Toast action with “failed” message.

  • Pingback: Retrofit Android Tutorial()

  • Omkar Amberkar

    What if we wanted to show the images in a GridView? What changes do we have to make in the MainActivity?

  • شبير البلوشي

    awesome. but i want to know how to implement onclicklistener. in next activity i wana show the extra details plus with image. do you have any tutorial for that.??

  • Pingback: Flipboard in Android using Retrofit()

  • Gustavo Adolfo Zuluaga C.

    Thanks a lot!

    • makeinfo14

      welcome :disqus :)

  • Java Pro
    • makeinfo14

      welcome :)

  • Subham Gupta

    I’m getting an error “Required JSON array but found string at coloumn1 line 1 path$”.
    Can anyone help please??

  • The Prophet

    Picasso is awesome but Glide? it`s more then awesome, it`s just a dreamlike loader that can do what picasso can`t. Example: loading of 21mp image with transform in HD completed in about seconds… while picasso needed minute or two to load that size, quality? quality was exact same (PREFFER_ARGB_8888) and it`s quite customizable too. so using 2 library to catch on Glide is nonsense while it`s AIO. size comparison is quite little too. 312kb is just nothing

  • Sophie Marry

    Great tutorial, easy to understand and implement, found it too useful

    Now, I have to parse below JSON :

    {
    “flowers”: [
    {
    “title”: “LOVE FLOWERS”,
    “items” : [
    {
    “item” : “RED FEEL ROSE”
    },
    {
    “item” : “RED CHARM ROSE”
    }
    ]
    },
    {
    “title”: “FRIENDSHIP FLOWERS”,
    “items” : [
    {
    “item” : “YELLOW ATTRACTION”
    },
    {
    “item” : “YELLOW FELLOWSHIP”
    }
    ]
    }
    ]
    }

    Please create another tutorial or share sample code with me if possible, because its bit urgent for me…

    Thanks