retrofit android example

Retrofit Android Example With Recyclerview [Download]

In this Retrofit Android tutorial, I am going to explain how to use Retrofit REST client to consume the Rest Web services.Basically, Retrofit developed by square and It’s a type-safe REST client for Android.

Advantages of Android Retrofit

  •      Retrofit android is dead-simple to use. It essentially lets you treat API calls as simple Java method calls, so you only define which URLs to hit and the types of the request/response parameters as Java classes.  
  •      The entire network call + JSON/XML parsing is completely handled by it (with help from Gson for JSON parsing), along with support for arbitrary formats with pluggable serialization/deserialization.

Android Retrofit Speed

Compare with Volley and AsyncTask, Retrofit providing the very fast response to the request.

retrofit speed comparision

Let’s get into the code part,

First, We have to add the retrofit dependency into our build.grade file. We can find the latest retrofit version in the official retrofit website. http://square.github.io/retrofit/

compile 'com.squareup.retrofit2:retrofit:2.3.0'

And the GSON converter from retrofit used to convert the JSON response from the server.

compile 'com.squareup.retrofit2:converter-gson:2.3.0'

Add Internet Permission to your Application in AndroidManifest.xml,

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

Create the Retrofit instance

We need to create the Retrofit instance to send the network requests. we need to use the Retrofit Builder class and specify the base URL for the service.

ApiClient.java

public class ApiClient {
    public static String BASE_URL ="http://velmm.com/apis/";
    private static Retrofit retrofit;
    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Setting Up the Retrofit Interface

Retrofit provides the list of annotations for each HTTP methods:

@GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.

The endpoints are defined inside of an interface using retrofit annotations to encode details about the parameters and request method. T return value is always a parameterized Call<T>.

Because the POJO classes are wrapped into a typed Retrofit Call class.

Method Parameters :

@Body – Sends Java objects as the request body.

@Url – use dynamic URLs.

@Query – We can simply add a method parameter with @Query() and a query parameter name, describing the type.

To URL encode a query using the form:
@Query(value = “auth_token”,encoded = true) String auth_token

ApiInterface.java

public interface ApiInterface {

    @GET("volley_array.json")
    Call<List<Movie>> getMovies();
}

Creating Model Class Before creating the model, we need to know what type of response we will be receiving.

[  
   {  
      "id":"1",
      "image":"http://velmm.com/images/bottom_navigationview/coco.jpg",
      "title":"Coco"
   },
   {  
      "id":"2",
      "image":"http://velmm.com/images/bottom_navigationview/terminator_2.jpg",
      "title":"Terminator 2: Judgment Day 3D"
   },
   {  
      "id":"3",
      "image":"http://velmm.com/images/bottom_navigationview/dunkirk.jpg",
      "title":"Dunkirk"
   },
   {  
      "id":"4",
      "image":"http://velmm.com/images/bottom_navigationview/the_salesman.jpg",
      "title":"The Salesman"
   },
   {  
      "id":"5",
      "image":"http://velmm.com/images/bottom_navigationview/lion.png",
      "title":"Lion"
   },
   {  
      "id":"6",
      "image":"http://velmm.com/images/bottom_navigationview/star_war.jpg",
      "title":"Star Wars: The Last Jedi"
   },
   {  
      "id":"7",
      "image":"http://velmm.com/images/bottom_navigationview/thor_ragnarok.jpg",
      "title":"Thor: Ragnarok"
   },
   {  
      "id":"8",
      "image":"http://velmm.com/images/bottom_navigationview/blade_runner_2049.jpg",
      "title":"Blade Runner 2049"
   },
   {  
      "id":"9",
      "image":"http://velmm.com/images/bottom_navigationview/borg_mcenroe.jpg",
      "title":"Borg McEnroe"
   },
   {  
      "id":"10",
      "image":"http://velmm.com/images/bottom_navigationview/wonder.jpg",
      "title":"Wonder"
   }
]

In my JSON response, I am having the list of movies with name, year and director properties. So, My Model class will be like Movie as class name and name, year, director are properties.

Movie.java

class Movie {

    @SerializedName("title")
    private String title;

    @SerializedName("image")
    private String imageUrl;

    public Movie(String title, String imageUrl) {
        this.title = title;
        this.imageUrl = imageUrl;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

@SerializedName is used to map the POJO object into to JSON response properties.


shimmer effect For Android Recyclerview Example

Android SwipeRefreshLayout with Recyclerview example


Consume the REST web service

All the setup are done. Now we are ready to consume the REST web service. In Our MainActivity.Java, First, need to initialize the ApiClient.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

After the initialization, we to call the getMovies() interface and implement the CallBacks. Part of the Implementation we need to override the onResponse() and onFailure().

If the request succeeds the callback will come into onResponse(). If any error in the request the callback will go into onFailure() method. In onResponse() method, we can get our response from response body.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<Movie>> call = apiService.getMovies();
call.enqueue(new Callback<List<Movie>>() {
    @Override
    public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
    }   

    @Override
    public void onFailure(Call<List<Movie>> call, Throwable t) {
        Log.d("TAG","Response = "+t.toString());
    }
});

Now our data is ready, then I am going to set the data into the Recyclerview.

Setup Recyclerview

adding the Recyclerview dependency into our build.grade file.

compile 'com.android.support:recyclerview-v7:26.1.0'

Android Recyclerview Material Design with Example

Expandable Recyclerview For Android With Example


Create the Recyclerview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.velmurugan.retrofitexample.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</LinearLayout>

create the Recyclerview adapter

RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyviewHolder> {

    Context context;
    List<Movie> movieList;

    public RecyclerAdapter(Context context, List<Movie> movieList) {
        this.context = context;
        this.movieList = movieList;
    }

    public void setMovieList(List<Movie> movieList) {
        this.movieList = movieList;
        notifyDataSetChanged();
    }

    @Override
    public RecyclerAdapter.MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_layout,parent,false);
        return new MyviewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.MyviewHolder holder, int position) {
        holder.tvMovieName.setText(movieList.get(position).getTitle());

        Glide.with(context).load(movieList.get(position).getImageUrl()).apply(RequestOptions.centerCropTransform()).into(holder.image);
    }

    @Override
    public int getItemCount() {
        if(movieList != null){
            return movieList.size();
        }
        return 0;

    }

    public class MyviewHolder extends RecyclerView.ViewHolder {
        TextView tvMovieName;
        ImageView image;

        public MyviewHolder(View itemView) {
            super(itemView);
            tvMovieName = (TextView)itemView.findViewById(R.id.title);
            image = (ImageView)itemView.findViewById(R.id.image);
        }
    }
}

recyclerview_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textViewMovieName"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:padding="5dp"
        android:gravity="center_vertical"
        android:textColor="@color/cardview_dark_background"
        android:layout_weight="1"
        android:text="TextView" />
</LinearLayout>

Recylerview is ready. Now I am going to set the data that we got from the response into the Recyclerview.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<Movie>> call = apiService.getMovies();

call.enqueue(new Callback<List<Movie>>() {
    @Override
    public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
        movieList = response.body();
        Log.d("TAG","Response = "+movieList);
        recyclerAdapter.setMovieList(movieList);
    }

    @Override
    public void onFailure(Call<List<Movie>> call, Throwable t) {
        Log.d("TAG","Response = "+t.toString());
    }
});

The final MainActivity.java

MainActivity.java
public class MainActivity extends AppCompatActivity {

    List<Movie> movieList;
    RecyclerView recyclerView;
    RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        movieList = new ArrayList<>();
        recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerAdapter = new RecyclerAdapter(getApplicationContext(),movieList);
        recyclerView.setAdapter(recyclerAdapter);

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call<List<Movie>> call = apiService.getMovies();

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                movieList = response.body();
                Log.d("TAG","Response = "+movieList);
                recyclerAdapter.setMovieList(movieList);
            }

            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d("TAG","Response = "+t.toString());
            }
        });
    }
}

Android ConstraintLayout Example

Create Reusable Alert Dialog in Android


Screenshot

Retrofit android example screenshot

 

github_link

9 thoughts on - Retrofit Android Example With Recyclerview [Download]

Leave a Reply

Your email address will not be published. Required fields are marked *