You are currently viewing GET request using retrofit in Android Tutorial

GET request using retrofit in Android Tutorial

In this tutorial, we will learn about retrofit and making a GET request using the retrofit library, we will implement Glide Library also for image loading. Retrofit is the most amazing library for android that seamlessly handles all the HTTP requests and responses.

Retrofit is a REST Client for Java and Android developed by Square Inc under the Apache 2.0 license. It is a straightforward network library that is used for network transactions. We can capture JSON responses from web services/web APIs using this library. It is a simple and quick library for retrieving and uploading data (JSON or other structured data) via a REST-based web service.

Output

Retrofit classes

  • Model class – The objects to be obtained from the JSON file are stored in this class.
  • Retrofit instance – This Java class is used to make API requests.
  • The interface class in Java is used to define endpoints.
Pros of Retrofit Cons of Retrofit
It is extremely fast.
It allows you to communicate directly with the web service.
It is simple to use and comprehend.
It accepts post requests as well as multipart uploads.
It is capable of handling both synchronous and asynchronous network requests.
It does not support the loading of images. It necessitates the use of additional libraries such as Glide and Picasso.
It does not allow you to set priorities.

What is Glide?

Glide is an Image Loader Library for Android developed by bumptech and is a Google-recommended library. It’s been used in a number of Google open-source projects. It supports animated GIFs and handles image loading/caching.

Glide is an open-source media management and image loading framework for Android that wraps media decoding, memory and disc caching, and resource pooling into a simple and easy-to-use interface.

Prerequisite

You should know the basic knowledge of android apps, folder structures, debugging, and running applications.

Requirements

  • To get the most recent news, you’ll need to use a third-party API.
  • Retrofit library is required to call that API.
  • Call the API, get the response, and store it in RecyclerView.
  • Glide library is required for Image loading.

In this example, I’m using the https://newsapi.org/ site to get the API(Free).
To use this API, we need an API KEY, which we can obtain by registering at https://newsapi.org/register.
you will receive an API KEY after a successful registration.

We should call the API given below using this API Key.

https://newsapi.org/v2/top-headlines?country=in&apiKey=API_KEY

Let’s begin with an Android Studio.

  • Open Android Studio and create a new Android project.
  • Open the build.gradle(app) file
  • In this project, we will use Retrofit to call the API.
  • Use RecyclerView to display the Response list.
  • In this project, we will use Glide library for image loading.

dependency:

    
    //Glide library dependency
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'

    //recycler view dependency
    implementation "androidx.recyclerview:recyclerview:1.2.1"

    // retrofit library dependency
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.0'

Because we work with network operations and other such things, we require Internet connection permission.
As a result, we must include Internet permission in AndroidManifest.xml.

//Internet Permission

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

Below is the code of the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sagar.retrofitexample">

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.RetrofitExample">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

In general, we require 3 classes to use the retrofit library –

  • Retrofit Builder Class: Build a retrofit instance that sends any HTTP request.
  • Model class: JSON representation in java.
  • The interface class in Java is used to define endpoints.

Create an instance of Retrofit

To send a request to the API, we must first create a retrofit instance. So, in the rest package, create a class called NewsService and write the code given below to create a retrofit instance. When creating an instance, we must specify the base URL for all requests. The base URL, in this case, is “https://newsapi.org/”.

package com.sagar.retrofitexample

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query

const val BASE_URL = "https://newsapi.org/"
const val API_KEY = "Place your API KEY here"

interface NewsInterface {
    @GET("v2/top-headlines?apikey=$API_KEY")
    fun getHeadline(@Query("country") country: String, @Query("page") page: Int) : Call<News>

}
object NewsService{
    val newsInstance: NewsInterface
    init {
        val retrofit= Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        newsInstance = retrofit.create(NewsInterface::class.java)
    }
}

addConverterFactory(GsonConverterFactory.create())
The Converter dependency includes a GsonConverterFactory class. Then invoke the class creates instance method. It is accomplished by calling create() on our retrofit instance and invoking the addConverterFactory method ().
It will automatically map JSON data to your Java Object.

Create Model class

We need to know what the model class’s content will be before we create it. In Java, the Model class represents JSON. As a result, we must understand the contents of JSON. The JSON URL that we will be using in this tutorial is

https://newsapi.org/v2/top-headlines?country=in&apiKey=086cbf45755841b6a4cf18b75a2898cf
  • Create a News data class by observing the response.
package com.sagar.retrofitexample

data class News(val totalResult: Int, val articles: List<Article>)
  • Now Create Article data class
package com.sagar.retrofitexample

data class Article(val author:String, val title: String, val description: String, val url: String, val urlToImage: String)

Adding RecyclerView into xml file

Because we saved the result in a RecyclerView, we need to create a RecyclerView. To do so, we must first declare it in activity main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recyclerView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Create item for recyclerView

To use the android retrofit library with the recyclerView, we must first define a layout for an item in the recyclerView.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="wrap_content"
    android:layout_margin="16dp"
    android:elevation="8dp"
    android:orientation="vertical"
    >

    <LinearLayout
        android:padding="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


        <ImageView
            android:id="@+id/newsimage"
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:padding="16dp"
            android:scaleType="centerCrop"
            tools:srcCompat="@tools:sample/avatars" />

        <TextView
            android:id="@+id/newstitle"
            style="@style/TextAppearance.AppCompat.Headline"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:ems="10"
            android:maxLines="2"
            android:text="TextView" />

        <TextView
            android:id="@+id/newsDescription"
            style="@style/TextAppearance.AppCompat.Body1"
            android:layout_width="match_parent"

            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:maxLines="2"
            android:text="TextView" />
    </LinearLayout>
</androidx.cardview.widget.CardView>

Create a RecyclerView Adapter

We have completed some basic setups to use the android retrofit library with recyclerView. We will now create an adapter that will provide data to the recyclerView. Now we must create an adapter class for RecyclerView.

package com.sagar.retrofitexample

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class NewsAdapter(val context: Context, val articles: List<Article>) :
    RecyclerView.Adapter<NewsAdapter.ArticleViewHolder>() {


    class ArticleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var newsImage = itemView.findViewById<ImageView>(R.id.newsimage)
        var newsTitle = itemView.findViewById<TextView>(R.id.newstitle)
        var newsDescription = itemView.findViewById<TextView>(R.id.newsDescription)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.news_item, parent, false)
        return ArticleViewHolder(view)
    }

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
        val article = articles[position]
        holder.newsTitle.text = article.title
        holder.newsDescription.text = article.description
        Glide.with(context).load(article.urlToImage).into(holder.newsImage)
        holder.itemView.setOnClickListener {
            Toast.makeText(context,article.title,Toast.LENGTH_SHORT).show()
        }
    }

    override fun getItemCount(): Int {
        return articles.size
    }
}

We defined three methods in the RecyclerView Adapter class (onCreateViewHolder(), onBindViewHolder(), and getItemCount()).

  • onCreateViewHolder() method – Creates an item view
  • onBindViewHolder() method – Binds data for a view
  • getItemCount() method – Returns the total number of items in the list

Make a GET request/ Make an HTTP request with the Retrofit Library.

So far, we’ve successfully created an adapter, an API service, a model class instance, and UI, items in recyclerView. Now we’ll look at how to make an HTTP request with the retrofit library.
Using the retrofit library, we can send GET, PUT, POST, PATCH, and DELETE requests. In this android application, we will now make an HTTP request using the retrofit library.

We’ll use retrofit to make a GET request that returns all data.

Finally, if the information is not successfully loaded into the RecyclerView, we will have an onFailure method that will display a Toast message.

Insert the following code into your MainActivity.

package com.sagar.retrofitexample

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {
    lateinit var adapter: NewsAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getData()

    }

    private fun getData() {

        val news = NewsService.newsInstance.getHeadline("in", 1)
        news.enqueue(object : Callback<News> {
            override fun onResponse(call: Call<News>, response: Response<News>) {
                val news = response.body()
                if (news!= null){
                    adapter = NewsAdapter(this@MainActivity,news.articles)
                    findViewById<RecyclerView>(R.id.recyclerView).adapter =adapter
                    findViewById<RecyclerView>(R.id.recyclerView).layoutManager = LinearLayoutManager(this@MainActivity)
                }

            }

            override fun onFailure(call: Call<News>, t: Throwable) {
                Toast.makeText(applicationContext, "Error Occured", Toast.LENGTH_LONG).show();
            }
        })
    }
}

Run the application now. You will get the output shown in the output section.

  • We hope that this guide will assist you in quickly creating a News Application using retrofit library in android. We concentrated on making a simple application for this tutorial. If you have any problems, please post them in the comments section, we will gladly assist you.

This Post Has One Comment

Leave a Reply