Android Retrofit Example Kotlin

06-Dec-2024

Android Retrofit Example Kotlin



1/  Create a new project .

main_activity.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/white"
>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recelerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

</RelativeLayout>



2/ Add dependencies

>>>build.gradle.kts(Module:app)



////////////////Retrofit in android////////////
implementation ("com.squareup.retrofit2:converter-gson:2.8.1") //Add Library for retrofit here
implementation ("com.squareup.retrofit2:retrofit:2.9.0")
//////////////////picasso in android/////////
implementation ("com.squareup.picasso:picasso:2.8")
// OkHttp logging interceptor (optional)
implementation ("com.squareup.okhttp3:logging-interceptor:4.10.0")




3/  Create a new Kotlin Class.

>>> DataModel.kt


package com.bangladeshplayer.bangladeshplayer

data class DataModel(
val player_name: String,
val player_catagory: String,
val player_age: String,
val player_avater: String

)



4/  Create a new Interface 

>>>RetrofitService



package com.bangladeshplayer.bangladeshplayer

import retrofit2.http.GET

interface RetrofitService {
@GET("playerinfo.json") ////Use your api endPoint
suspend fun getAllplayer(): List<DataModel>
}


5/  Create a new object.

>>>RetrofitInstance.kt



package com.bangladeshplayer.bangladeshplayer

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitInstance {
private const val BASE_URL = "http://codewithbiozid10.atwebpages.com/"////put your base Url
val api: RetrofitService by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(RetrofitService::class.java)
}
}

6/  Create a new Adapter.

>>>PlayerAdapter.kt





package com.bangladeshplayer.bangladeshplayer

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso

class PlayerAdapter(private val dataList: List<DataModel>) : RecyclerView.Adapter<PlayerAdapter.PalyerViewHolder>() {

class PalyerViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val player_name: TextView = view.findViewById(R.id.player_name)
val player_catagory: TextView = view.findViewById(R.id.player_catagory)
val player_age: TextView = view.findViewById(R.id.player_age)
val player_avater: ImageView = view.findViewById(R.id.player_avater)
}

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

override fun onBindViewHolder(holder: PalyerViewHolder, position: Int) {
val dataModel = dataList[position]
holder.player_name.text = dataModel.player_name
holder.player_catagory.text = dataModel.player_catagory
holder.player_age.text = dataModel.player_age
holder.player_age.text = dataModel.player_age
val imageurl: String=dataModel.player_avater
Picasso.get()
.load(""+imageurl)
.placeholder(R.drawable.ic_launcher_background) // Image shown while loading
.error(R.drawable.ic_launcher_background) // Image shown on error
.into(holder.player_avater)


}

override fun getItemCount() = dataList.size
}


7/  Create a new Layout Resource File.

>>> item_layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
android:id="@+id/contentLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/bottom_shade"
android:paddingBottom="10dp"
android:layout_margin="10dp"
android:clickable="true"
android:foreground="?attr/selectableItemBackground"

>

<ImageView
android:id="@+id/player_avater"
android:layout_width="180dp"
android:layout_height="250dp"
android:scaleType="centerCrop"
android:layout_margin="5dp"
android:src="@mipmap/ic_launcher"
/>

<LinearLayout
android:layout_marginStart="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="left|center"

>
<TextView
android:id="@+id/player_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textStyle="bold"
android:textSize="25sp"
android:layout_marginTop="5dp"
android:textColor="@color/black"

/>
<TextView
android:id="@+id/player_catagory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="23sp"
android:layout_marginTop="3dp"
android:textStyle="bold"
android:textColor="#009688"


/>
<TextView
android:id="@+id/player_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="22sp"
android:layout_marginTop="3dp"
android:textStyle="bold|italic"
android:textColor="@color/black"


/>

</LinearLayout>


</LinearLayout>

</LinearLayout>



8/  MainActivity.kt




package com.bangladeshplayer.bangladeshplayer

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

private lateinit var recyclerView: RecyclerView
private lateinit var adapter: PlayerAdapter


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView=findViewById(R.id.recelerView)

recyclerView = findViewById(R.id.recelerView)
recyclerView.layoutManager = LinearLayoutManager(this)
DataRequest()

}




private fun DataRequest(){


CoroutineScope(Dispatchers.IO).launch {
try {
val datamodel = RetrofitInstance.api.getAllplayer()
withContext(Dispatchers.Main) {
adapter = PlayerAdapter(datamodel)
recyclerView.adapter = adapter
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}


9/  Internet Permissoin .

>>>In Menifest




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:networkSecurityConfig="@xml/network_security_config"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BangladeshPlayer"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>


10/  In a Optional XML file create if you need.

if your use free api or http Api.

this is are

>>>>network_security_config.xml



<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">codewithbiozid10.atwebpages.com</domain>
</domain-config>
</network-security-config>



Comments