Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Android - JSON Parsing Using Retrofit Library with Jetpack Compose
Next article icon

Android - JSON Parsing using Retrofit Library with Kotlin

Last Updated : 04 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 


Next Article
Android - JSON Parsing Using Retrofit Library with Jetpack Compose

C

chaitanyamunje
Improve
Article Tags :
  • Kotlin
  • Android

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences