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?

More than 1 year has passed since last update.

a-4-2-1.Retrofit2を使ったGETのAPIアクセス

Last updated at Posted at 2023-09-27

a-4-2-1.Retrofit2を使ったGETのAPIアクセス

目標設定

一覧に戻る

課題

  1. Retrofit2でGETメソッドのAPIの呼び出しができるか。
  2. Retrofit2のGETメソッドでURLクエリを取得できるか。
  3. Retrofit2のGETメソッドで戻り値を取得できるか。

Github

テスト実装

Retrofit2TestActivity.kt
class Retrofit2TestActivity : AppCompatActivity() {
    private lateinit var binding: ActivityRetrofit2TestBinding
    private var retrofit2TestService: Retrofit2TestService = Retrofit2TestService()

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

        binding.gettingApiButton.stateListAnimator = null;
        binding.gettingApiButton.setOnClickListener {
            // 1. Retrofit2でGETメソッドのAPIの呼び出しができるか。
            // ・可能でした。
            retrofit2TestService.getApiAccess().getTest1Table(3)
                .enqueue(object : Callback<Retrofit2TestService.Api2Response> {
                    override fun onResponse(
                        call: Call<Retrofit2TestService.Api2Response>,
                        response: Response<Retrofit2TestService.Api2Response>
                    ) {
                        val colum2: String = response.body()?.data?.colum2 ?: ""
                        Log.d("Retrofit2TestActivity", "colum2=${colum2}")
                        showMessage(response.body().toString())
                    }

                    override fun onFailure(
                        call: Call<Retrofit2TestService.Api2Response>,
                        t: Throwable
                    ) {
                        Log.d("Retrofit2TestActivity", t.message ?: "APIエラー")
                    }
                })
        }
        ...
    }
    fun showMessage(message: String) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Retrofit2の検証")
            .setMessage(message)
            .setPositiveButton("OK") { _, _ ->

            }
        builder.create()
        builder.show()
    }
}
activity_retrofit2_test.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/linear_layout1"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="4dp">

        <TextView
            android:id="@+id/text_1_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="0dp"
            android:text="Retrofit2の検証"
            android:textSize="21sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="HardcodedText" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="4dp" />

        <LinearLayout
            android:id="@+id/linear_layout2"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/getting_api_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/style3_button_background"
                app:backgroundTint="@null"
                android:text="GETの\nAPIアクセス"
                android:padding="8dp"
                android:textSize="11sp"
                tools:ignore="HardcodedText" />

            <Space
                android:layout_width="4dp"
                android:layout_height="match_parent" />

            <Button
                android:id="@+id/posting_api_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/style3_button_background"
                app:backgroundTint="@null"
                android:text="POSTの\nAPIアクセス"
                android:padding="8dp"
                android:textSize="11sp"
                tools:ignore="HardcodedText" />
        </LinearLayout>

        <Space
            android:layout_width="match_parent"
            android:layout_height="4dp" />

        <Button
            android:id="@+id/deleting_api_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/style3_button_background"
            app:backgroundTint="@null"
            android:text="DELETEの\nAPIアクセス"
            android:padding="8dp"
            android:textSize="11sp"
            tools:ignore="HardcodedText" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Retrofit2TestService.kt
class Retrofit2TestService {
    interface APIInterface {
        // 2. Retrofit2のGETメソッドでURLクエリを取得できるか。
        // ・可能でした。
        @GET("api2_get_test1_table.php")
        fun getTest1Table(@Query("colum1") colum1: Int?): Call<Api2Response>
    ...
    }

    // 3. Retrofit2のGETメソッドでBodyの値を取得できるか。
    // ・可能でした。
    data class Api2Response(
        @SerializedName("data") val data: Api2ResponseData
        ): Serializable
    data class Api2ResponseData(
            @SerializedName("COLUM1") val colum1: Int,
            @SerializedName("COLUM2") val colum2: String
        ): Serializable
    ...
    companion object {
        private const val BASE_URL = "https://wakizaka24.sakura.ne.jp/reversi/php/"
    }

    private var apiInterfaceImpl: APIInterface

    init {
        val gsonFactory = GsonConverterFactory.create(
            GsonBuilder().serializeNulls().create())
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(gsonFactory)
            .build()
        apiInterfaceImpl = retrofit.create(APIInterface::class.java)
    }

    fun getApiAccess(): APIInterface {
        return apiInterfaceImpl
    }
}
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?