In this example, I will show you how to call json service using Retrofit2 to post user data and display response into TextView.
Kotlin Call Service Using Retrofit2 Method Post Example
Creating a New Project
- So first create a new Android Studio project using Kotlin.
- Once the project is loaded come inside the activity_main.xml and remove the Hello World TextView.
Android studio project screen
JSON Service Url:
Step 1:
Open build.gradle and add following dependency and rebuild the project.
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.google.android.material:material:1.2.0'
Step 2:Open AndroidManifest.xml and add Internet Permission.<uses-permission android:name="android.permission.INTERNET"/>Step 3:Create new Package:- modelUsersDataModel.ktCreate new class UsersDataModel.kt under model package and Add following code.package com.kotlinkatta.retrofitget.model
import com.google.gson.annotations.SerializedName
data class UsersDataModel(
@SerializedName("id")
val id: Int? = null,
@SerializedName("createdAt")
val createdAt: String? = null,
)Step 4:Create new Package:- retofitdataDataService.ktCreate new class DataService.kt under retofitdata package and Add following code.package com.kotlinkatta.retrofitget.retofitdata
import com.kotlinkatta.retrofitget.model.UsersDataModel
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface DataService {
@POST("/api/users")
@FormUrlEncoded
fun savePost(
@Field("title") title: String,
@Field("body") body: String,
@Field("userId") userId: Long
): Call<UsersDataModel>
}Step 5:RetrofitClient.ktCreate new class RetrofitClient.kt under retofitdata package and Add following code.package com.kotlinkatta.retrofitget.retofitdata
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
var retrofit: Retrofit? = null
var base_url = "https://reqres.in"
val retrofitInstance: Retrofit
get() {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit!!
}
}Step 6:MainActivity.ktAdd following code into MainActivity.kt.package com.kotlinkatta.retrofitpost
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import com.kotlinkatta.retrofitget.model.UsersDataModel
import com.kotlinkatta.retrofitget.retofitdata.DataService
import com.kotlinkatta.retrofitget.retofitdata.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
lateinit var txt_response: TextView
lateinit var progress_bar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progress_bar = findViewById<ProgressBar>(R.id.progress_bar)
txt_response = findViewById<TextView>(R.id.txt_response)
funPostUsersData()
}
private fun funPostUsersData() {
progress_bar.visibility = View.VISIBLE
val service: DataService = RetrofitClient.retrofitInstance!!.create(DataService::class.java)
val call: Call<UsersDataModel> = service.savePost("title","body",1)
call.enqueue(object : Callback<UsersDataModel> {
override fun onResponse(call: Call<UsersDataModel>, response: Response<UsersDataModel>) {
Toast.makeText(applicationContext,"Data Send Successfully",Toast.LENGTH_SHORT).show()
txt_response.setText("Id : "+response.body()!!.id +"\nCreated At : "+response.body()!!.createdAt)
progress_bar.visibility = View.GONE
}
override fun onFailure(call: Call<UsersDataModel>, t: Throwable?) {
progress_bar.visibility = View.GONE
}
})
}
}Step 7:activity_main.xmlAdd following code into activity_main.xml.<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<TextView
android:id="@+id/txt_response"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:layout_gravity="center"
android:gravity="center"
android:textSize="20dp"/>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>OutPut:
Comments
Post a Comment