Use Retrofit & Gson in Android With Kotlin

In this tutorial we will learn, How to Use Retrofit Library With Gson Android using Kotlin.Want to make your HTTP calls faster and smoother use retrofit. Volley is also good http calls library.

What Is Retrofit?

Retrofit is library which converts your HTTP API into a Java Interface. It’s a best practice to use retrofit library to your android application.

How To Use Retrofit With Kotlin?

steps are given below.

Step 1.  Create  a new Android Studio project or File | New project 

Use Retrofit in Android With Kotlin

If you dont aware much with Kotlin Please refer Get Started with kotlin. For Basic of Kotlin refer post Basics of Kotlin and Kotlin Operators.

 

 

 

 

 

Step 2. In build.gradle(Module:app) 

Step 3.  Add permissions in AndroidManifest.xml

For Making Use of internet we need to add INTERNET permission.

Step 4. ApiInterface.kt

Step 5. Category.kt

This Model or POJO for category.


Step 6. CategoryResponse.kt

this class is for converting json response to model. same way you need to create request class if you need to pass some data with

 

Step 7. activity_main.xml


Step 8. MainActivity.kt

OUTPUT

   

DOWNLOAD SOURCE CODE

Other annotations:

  • @Path – Used to add variables in url for generally used with GET request

EXAMPLE

Base Url = https://androidteachers.com/

your service full url is https://androidteachers.com/XXX/getCategory.php

  • @GET(“movie/{XXX}”)
    Call<PostResponse> getCategory(@Path(“XXX”) int id, @Query(“filter”) String
  • @Query – Its url paramters after ? in url. its key value pair.

EXAMPLE : https://androidteachers.com/XXX/getPost.php?filter=android

  • @Body – Payload for the POST call, Need to create class for request.
  • @Header – adding params in header, like Content-Type= application/json or need to pass access token

2548total visits,209visits today

Related posts

Leave a Comment