0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Retrofitで通信する方法

Posted at

Androidアプリでサーバーからデータを取得する処理は欠かせません。Retrofitを使って、APIから取得する方法をメモします。
取得元APIは JSONPlaceholder(無料のAPI)を使用します。

依存関係の追加

build.gradle に以下を追加します。

dependencies {
    implementation("com.squareup.retrofit2:retrofit:x.x.x")
    implementation("com.squareup.retrofit2:converter-gson:x.x.x")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x")
}

このデータをマッピングするデータクラスを作ります。

data class User(
    val id: Int,
    val name: String,
    val email: String
)

Retrofitのインターフェイスを定義

@GET アノテーションに相対パスを指定します。 suspend を付けることでコルーチン対応になります。

import retrofit2.http.GET

interface ApiService {
    @GET("users/1")
    suspend fun getUser(): User
}

Retrofitクライアントを作る

Retrofitのインスタンスを生成します。

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

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

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

Activityでデータを取得して表示

Activityを作成して、取得したデータを TextView に表示します。lifecycleScope.launch {} 内で suspend 関数を呼び出します。API通信が成功すると、TextView にユーザー情報が表示されます。

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.example.retrofitdemo.databinding.ActivityMainBinding
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        lifecycleScope.launch {
            try {
                val user = RetrofitClient.apiService.getUser()
                binding.textView.text = "Name: ${user.name}\nEmail: ${user.email}"
            } catch (e: Exception) {
                binding.textView.text = "Error: ${e.message}"
            }
        }
    }
}

実行結果

ネットワーク通信が実行され、以下のように表示されます。これでRetrofitを使ったAPI通信の完成です。

Name: Leanne Graham
Email: Sincere@april.biz

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?