Android - JSON Parsing using Retrofit Library with Kotlin
Last Updated : 04 Jul, 2022
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look at JSON Parsing in Android applications using Kotlin.
Note: If you are looking to implement JSON Parsing in Android using Retrofit in Java language. Check out the following article: JSON Parsing in Android using Retrofit Library with Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below dependency for using retrofit. implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' // below dependency for using picasso image loading library implementation 'com.squareup.picasso:picasso:2.71828'
After adding this dependency simply sync your project to install it.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML <!--permissions for INTERNET--> <uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML <?xml version="1.0" encoding="utf-8"?> <!--on below line we are creating a swipe to refresh layout--> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" android:orientation="vertical" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <!--on below line we are creating a simple card view--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/idBtnVisitCourse" android:orientation="vertical"> <!--on below line we are creating a image view--> <ImageView android:id="@+id/idIVCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" /> <!--on below line we are creating our text view--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp" android:padding="4dp" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> <!--on below line we are creating one more text view--> <TextView android:id="@+id/idTVPreq" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="4dp" android:padding="4dp" android:textColor="@color/black" android:textStyle="bold" /> <!--on below line we are creating a text view for description--> <TextView android:id="@+id/idTVDesc" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="4dp" android:padding="4dp" android:textColor="@color/black" /> </LinearLayout> <!--on below line we are creating a progress bar--> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> <!--on below line we are creating a button to visit our course--> <Button android:id="@+id/idBtnVisitCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_margin="4dp" android:padding="3dp" android:text="Visit Course" android:textAllCaps="false" android:visibility="gone" /> </RelativeLayout> </ScrollView>
Step 5: Creating a modal class for storing our data
Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class and name it as RecyclerData and add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin package com.gtappdevelopers.kotlingfgproject data class CourseDataModal( // on below line creating variables for our modal class // make sure that variable name should be same to // that of key which is used in json response. var courseName: String, var courseimg: String, var courseDesc: String, var Prerequisites: String, var courseLink: String )
Step 6: Creating an Interface class for our API Call
Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class select it as Interface and name the file as RetrofitAPI and add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin package com.gtappdevelopers.kotlingfgproject import retrofit2.Call import retrofit2.http.GET interface RetrofitAPI { // as we are making get request // so we are displaying GET as annotation. // and inside we are passing // last parameter for our url. @GET("8RFY") fun // as we are calling data from array // so we are calling it with json object // and naming that method as getCourse(); getCourse(): Call<CourseDataModal?>? }
Step 7: Working with the MainActivity.kt file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Kotlin package com.gtappdevelopers.kotlingfgproject import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.squareup.picasso.Picasso import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class MainActivity : AppCompatActivity() { // on below line we are creating variables for // our text view, image view and progress bar lateinit var courseNameTV: TextView lateinit var courseDescTV: TextView lateinit var courseReqTV: TextView lateinit var courseIV: ImageView lateinit var visitCourseBtn: Button lateinit var loadingPB: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // on below line we are initializing our variable with their ids. courseNameTV = findViewById(R.id.idTVCourseName) courseDescTV = findViewById(R.id.idTVDesc) courseReqTV = findViewById(R.id.idTVPreq) courseIV = findViewById(R.id.idIVCourse) visitCourseBtn = findViewById(R.id.idBtnVisitCourse) loadingPB = findViewById(R.id.idLoadingPB) // on below line we are creating a method // to get data from api using retrofit. getData() } private fun getData() { // on below line we are creating a retrofit // builder and passing our base url // on below line we are creating a retrofit // builder and passing our base url val retrofit = Retrofit.Builder() .baseUrl("https://jsonkeeper.com/b/") // on below line we are calling add Converter // factory as GSON converter factory. // at last we are building our retrofit builder. .addConverterFactory(GsonConverterFactory.create()) .build() // below line is to create an instance for our retrofit api class. // below line is to create an instance for our retrofit api class. val retrofitAPI = retrofit.create(RetrofitAPI::class.java) val call: Call<CourseDataModal?>? = retrofitAPI.getCourse() // on below line we are making a call. call!!.enqueue(object : Callback<CourseDataModal?> { override fun onResponse( call: Call<CourseDataModal?>?, response: Response<CourseDataModal?> ) { if (response.isSuccessful()) { // inside the on response method. // we are hiding our progress bar. loadingPB.visibility = View.GONE // on below line we are getting data from our response // and setting it in variables. val courseName: String = response.body()!!.courseName val courseLink: String = response.body()!!.courseLink val courseImg: String = response.body()!!.courseimg val courseDesc: String = response.body()!!.courseDesc val coursePreq: String = response.body()!!.Prerequisites // on below line we are setting our data // to our text view and image view. courseReqTV.text = coursePreq courseDescTV.text = courseDesc courseNameTV.text = courseName // on below line we are setting image view from image url. Picasso.get().load(courseImg).into(courseIV) // on below line we are changing visibility for our button. visitCourseBtn.visibility = View.VISIBLE // on below line we are adding click listener for our button. visitCourseBtn.setOnClickListener { // on below line we are opening a intent to view the url. val i = Intent(Intent.ACTION_VIEW) i.setData(Uri.parse(courseLink)) startActivity(i) } } } override fun onFailure(call: Call<CourseDataModal?>?, t: Throwable?) { // displaying an error message in toast Toast.makeText(this@MainActivity, "Fail to get the data..", Toast.LENGTH_SHORT) .show() } }) } }
Now run your application to see the output of it.
Output:
Similar Reads
JSON Parsing in Android using Retrofit Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specif
6 min read
JSON Parsing in Android Using Volley Library with Kotlin
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
5 min read
Android - JSON Parsing Using Retrofit Library with Jetpack Compose
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look
9 min read
Android - Extract Data From JSON Array using Retrofit Library with Kotlin
In the android application, the response from the server is in the form of JSON. We can get to see either a JSON Array or a JSON Object in the response. JSON Array is the list of data which is having similar JSON objects. In the previous article, we have taken a look at How to parse data from JSON O
7 min read
JSON Parsing in Android using Volley Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specif
6 min read
Android - JSON Parsing using Volley Library with Jetpack Compose
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
8 min read
Retrofit with Kotlin Coroutine in Android
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Android - SearchView with RecyclerView using Kotlin
Many apps display vast amounts of data within their in the form of a list and the user is not able to go through each item within the list to get the item that he wants. For filtering these lists within the android application we can use SearchView to filter it. In this article, we will be building
7 min read
XML Parsing in Android using DOM Parser
Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files. In General, a DOM parser loads the XML file into the Android memory to parse the XML doc
6 min read
Android - Extract Data From JSON Array using Volley Library with Kotlin
JSON responses are of 2 types i.e. JSON Object and JSON Array. JSON Array consists of individual JSON objects which are having same similar structure but have different values within it. JSON Array is used to parse the data in the form of a list or an array. In the previous article, we have taken a
7 min read