Retrofit2 | #1

Зависимости для build.gradle:

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"

Product.kt

data class Product(
val id: Int,
val title: String,
val description: String,
val price: Int,
val discountPercentage: Float,
val rating: Float,
val stock: Int,
val brand: String,
val category: String,
val thumbnail: String,
val images: List<String>
)

ProductApi.kt

import retrofit2.http.GET
import retrofit2.http.Path

interface ProductApi {
@GET("products/{id}")
suspend fun getProductById(@Path("id") id: Int): Product
}

Разрешение в манифест:

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

activity_main.kt

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.157" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import com.example.retrofitlesson.retrofit.ProductApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tv = findViewById<TextView>(R.id.tv)
val b = findViewById<Button>(R.id.button)

val retrofit = Retrofit.Builder()
.baseUrl("https://dummyjson.com")
.addConverterFactory(GsonConverterFactory.create()).build()
val productApi = retrofit.create(ProductApi::class.java)

b.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
val product = productApi.getProductById(3)
runOnUiThread {
tv.text = product.title
}
}
}
}
}

Добавить комментарий

Ваш адрес email не будет опубликован.