③Retrofit(RestAPIからデータを取得する)

Kotlin

build.gradle

dependencies {
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")
}

retrofit(非同期通信するためのライブラリ)をimplementします

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest>
    <uses-permission android:name="android.permission.INTERNET" />

インターネットに接続するのでパーミッションを追加します

com.exmple.myapp/network/ApiService.kt

package com.example.myapp.network

import retrofit2.Call
import retrofit2.http.GET
import com.example.myapp.model.CustomData

interface ApiService {
    @GET("wp-json/custom/v1/data")
    fun getData(): Call<List<CustomData>>
}

API インターフェースの概要を定義します

今回は @GET(“REST APIのパス”) つまりREST APIからデータをGETします。

サーバーからはCustomData.ktで定義したCustomDataオブジェクトのListがCall(呼び出し)されます。

そして関数getDataを使うことで、このListが得られるようにしておきます。

com.example.myapp/model/CustomData.kt

package com.example.myapp.model

import com.google.gson.annotations.SerializedName

data class CustomData(
    @SerializedName("id") val id: Int,
    @SerializedName("name") val name: String,
    @SerializedName("value") val value: String
)

データクラスを作成します。中身はカラム名に合わせます

com.example.myapp/network/RetrofitClient.kt

package com.example.myapp.network

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

object RetrofitClient { ※1
    val instance: ApiService by lazy {  ※2
        val retrofit = Retrofit.Builder()
            .baseUrl("https://your-website.com/")
            .addConverterFactory(GsonConverterFactory.create()) ※3
            .build() ※4
        retrofit.create(ApiService::class.java)  ※5
    }
}

Retrofitクライアント(インスタンスを持つオブジェクト)を作ります

※1 … object RetrofitClient {} とすることで、アプリ全体で1つのインスタンスしか存在しないクラスをつくります(今回はRetrofitClientというオブジェクトが持つインスタンス「instance」はアプリ全体に1つしか存在せず、これを使い回すことでメモリ消費を抑えています。)

※2 … by lazyは最初にアクセスされたときに初めてApiServiceのオブジェクトであるinstanceを定義することを意味します。メモリ消費やリソース節約に役立つらしいです。

※3 … APIのレスポンスはJSON形式なのでKotlinのオブジェクトに変換します

※4 … buildして設定を適用させます

※5 … ApiService.ktで定義したApiServiceを使ってinstanceをcreateします。これでinstance.getData()などでhttps://your-website.com/wp-json/custom/v1/data/からデータをゲットできるようになりました。getData()はApiService.ktで定義した関数名です。

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fetchData()
    }

    private fun fetchData() {
        RetrofitClient.instance.getData().enqueue(object: Callback<List<CustomData>> { ※1
            override fun onResponse(call: Call<List<CustomData>>, response: Response<List<CustomData>>) {
                if (response.isSuccessful) { ※3
                    response.body()?.let { data ->  ※4
                        data.forEach {
                            Log.d("API_RESPONSE", "ID: ${it.id}, NAME: ${it.name}, VALUE: ${it.value}")
                        }
                    }
                }
            }

            override fun onFailure(call: Call<List<CustomData>>, t: Throwable) { ※2
                Log.e("API_ERROR", "Error: ${t.message}")
            }
        })
    }
}

※1 … Retrofit.instance.getData()でhttps://xxx.com/wp-json/xxx にアクセスしてデータを取得します。

enqueueは非同期のHTTP通信を行うという意味です。executeとすると同期通信になります。

得られるデータはList<CustomData>という形になります。

※2 … 成功したらonResponse 、失敗したらonFailure 関数を実行します

※3 … レスポンスが成功(200等)かどうかを判別します

※4 … response.body() はAPIから返ってきたJSONデータをList<CustomData>というKotlinオブジェクトに変換したものです。これがnull出ない場合?.let {}内の処理を行います。

BACK