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.

Kotlin の例題 (JSON の List の処理)

Last updated at Posted at 2023-10-23

例題

次の機能を Kotlin で Retrofit2 を使って実装

get_first_title.sh
http https://jsonplaceholder.typicode.com/albums | jq .[0].title

実行結果

$ ./get_first_title.sh 
"quidem molestiae enim"

プロジェクトの作成

プロジェクト名を album01 としました。

環境設定

インターネットにアクセスできるようにします。

manifests/AndroidManifest.xml
(省略)
<uses-permission android:name="android.permission.INTERNET" />
(省略)

Retrofit2 を使う設定

app/build.gradle.kts
(省略)
dependencies {
val retrofit_version = "2.9.0"    implementation("com.squareup.retrofit2:retrofit:$retrofit_version")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
(省略)

画面

res/layout/activity_main.xml
<?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">


    <LinearLayout
        android:layout_width="409dp"
        android:layout_height="729dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Good Morning"
            android:textSize="30sp" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

プログラム

MainActivity.kt
package com.example.album01

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

data class Album(val userId: Int, val id: Int, val title: String)

interface ApiService {
    @GET("albums")
    suspend fun getAlbums(): List<Album>
}

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

        var textMessage = findViewById<TextView>(R.id.textView)

        val retrofit = Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val apiService = retrofit.create(ApiService::class.java)

        GlobalScope.launch(Dispatchers.IO) {
            try {
                val apiResponse = apiService.getAlbums()
                if (apiResponse.isNotEmpty()) {
                    println("*** launch *** aaa *** PM 13:15")
                    val firstAlbumTitle = apiResponse[0].title
                    println("" + firstAlbumTitle)
                    println("*** launch *** ccc *** PM 13:15")

                    textMessage.setText(firstAlbumTitle)

                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

実行結果

image.png

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?