free geoip
39

Kotlin Retrofit Not Making Network Calls Solution

If your Kotlin app using Retrofit isn’t making any network calls, it can be frustrating, especially during debugging or while…

If your Kotlin app using Retrofit isn’t making any network calls, it can be frustrating, especially during debugging or while building production-level apps. This issue often arises due to misconfigurations in Retrofit setup, incorrect coroutine usage, or missing permissions in AndroidManifest.xml. Here’s a step-by-step guide to fix it with a working example.

Kotlin Retrofit Not Making Network Calls

Step 1: Add Required Dependencies

Make sure you’ve added the correct Retrofit and converter dependencies in your build.gradle file:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1'

Step 2: Add Internet Permission

Update your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

Step 3: Create Data Model

data class Post(
    val userId: Int,
    val id: Int,
    val title: String,
    val body: String
)

Step 4: Define Retrofit API Interface

import retrofit2.http.GET
import retrofit2.Response

interface ApiService {
    @GET("posts")
    suspend fun getPosts(): Response<List<Post>>
}

Step 5: Build Retrofit Instance

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

object RetrofitClient {
    private const val BASE_URL = "https://jsonplaceholder.typicode.com/"

    val instance: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}

Step 6: Call API in ViewModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {

    fun fetchPosts() {
        viewModelScope.launch {
            try {
                val response = RetrofitClient.instance.getPosts()
                if (response.isSuccessful) {
                    val posts = response.body()
                    println("Success: ${posts?.size} posts loaded")
                } else {
                    println("Error: ${response.code()}")
                }
            } catch (e: Exception) {
                println("Exception: ${e.message}")
            }
        }
    }
}

Step 7: Trigger the Network Call in Activity

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.viewModels

class MainActivity : ComponentActivity() {

    private val viewModel: MainViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.fetchPosts()
    }
}

Common Mistakes That Cause No Network Calls:

  • Missing INTERNET permission.
  • Not using suspend functions in Retrofit interface.
  • Network call not triggered in ViewModelScope.
  • Forgetting to set correct baseUrl.
  • Network on main thread (if not using coroutines or proper async calls).

For further reading on common pitfalls, you can check out this useful Retrofit guide.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *