// Step 1: Open the `build.gradle` (Module: app) file in your Android Studio project.
// Step 2: Add the following dependencies for Retrofit and Gson converter in the `dependencies` block.
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
// Step 3: Sync your project to let Android Studio download the new dependencies.
// Step 4: (Optional) If not already present, add the internet permission to the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
// Step 5: Create a Retrofit instance in your code using the following snippet.
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/") // Replace with your API base URL
.addConverterFactory(GsonConverterFactory.create())
.build()
// Step 6: Define your API service interface using Retrofit annotations. For example:
interface ApiService {
@GET("endpoint")
suspend fun fetchData(): Response<DataModel>
}
// Step 7: Create an instance of your API service using the Retrofit instance.
val apiService = retrofit.create(ApiService::class.java)
// Step 8: Make API calls using the defined methods in your service interface. For example:
try {
val response = apiService.fetchData()
if (response.isSuccessful) {
val data = response.body()
// Handle the data
} else {
// Handle error
}
} catch (e: Exception) {
// Handle exception
}