ตอนที่ 10 Android Studio Kotlin การเชื่อมต่ออินเตอร์เน็ตด้วย HTTP(s)

ในโลกของการรับทำแอพมือถือ การดึงข้อมูลจากอินเทอร์เน็ตเป็นสิ่งสำคัญ ด้วยความต้องการที่เพิ่มขึ้นสำหรับการทำแอพที่ขับเคลื่อนด้วยข้อมูล จึงกลายเป็นเรื่องสำคัญที่จะต้องเข้าใจวิธีดึงข้อมูลจากอินเทอร์เน็ตโดยใช้คำขอ HTTP บทความนี้จะแนะนำคุณเกี่ยวกับการตั้งค่าโครงการ Android Studio ด้วย Kotlin เพื่อดึงข้อมูลจากอินเทอร์เน็ตโดยใช้คำขอ HTTP เราจะใช้ไลบรารียอดนิยม ‘Retrofit’ เพื่อจัดการกระบวนการทั้งหมดอย่างง่ายดาย

การเพิ่ม Dependencies

เราจะใช้ Retrofit สำหรับจัดการคำขอ HTTP และ Moshi สำหรับแยกวิเคราะห์ข้อมูล JSON หากต้องการเพิ่มการพึ่งพาเหล่านี้ ให้เปิดไฟล์ build.gradle ใน Android Studio ระดับแอปและรวมบรรทัดต่อไปนี้ไว้ในบล็อก dependencies:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.12.0'

ซิงค์โครงการเพื่อดาวน์โหลดและกำหนดค่าการพึ่งพา

การสร้างแบบจำลองข้อมูล (Data Model)

สมมติว่าเรากำลังดึงรายชื่อผู้ใช้จากอินเทอร์เน็ต เราจะสร้างคลาสข้อมูลเพื่อแสดงวัตถุผู้ใช้

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

การสร้างอินเทอร์เฟซ API

จากนั้น สร้างอินเทอร์เฟซเพื่อกำหนดจุดสิ้นสุดสำหรับการเรียก API

import retrofit2.http.GET

interface ApiService {
    @GET("users")
    suspend fun getUsers(): List<User>
}

คำอธิบายประกอบ @GET ระบุว่าคำขอนั้นเป็นคำขอ GET ฟังก์ชัน getUsers จะรับผิดชอบในการดึงรายชื่อผู้ใช้

การตั้งค่า Retrofit

ตอนนี้ สร้างคลาสชื่อ RetrofitInstance เพื่อตั้งค่า Retrofit ด้วย URL พื้นฐาน

import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

object RetrofitInstance {
    private const val BASE_URL = "https://api.example.com/"

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(MoshiConverterFactory.create())
        .build()

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

คลาสนี้ตั้งค่าอินสแตนซ์ Retrofit ด้วย URL พื้นฐานและตัวแปลง Moshi สำหรับการแยกวิเคราะห์ JSON มันเปิดเผยตัวแปร apiService ซึ่งเราจะใช้ในการเรียก API

การดึงข้อมูลจากอินเทอร์เน็ต

ใน MainActivity.ktให้สร้างฟังก์ชันชื่อfetchUsers()เพื่อดึงรายชื่อผู้ใช้โดยใช้ apiService

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Response

private fun fetchUsers() {
    GlobalScope.launch(Dispatchers.IO) {
        try {
            val response: Response<List<User>> = RetrofitInstance.apiService.getUsers()
            if (response.isSuccessful) {
                val users: List<User>? = response.body()
                withContext(Dispatchers.Main) {
                    // Update UI with the retrieved data
                }
            } else {
            withContext(Dispatchers.Main) {
                // Handle the error response
                Toast.makeText(
                    this@MainActivity,
                    "Error fetching data: ${response.errorBody()}",
                    Toast.LENGTH_SHORT
                ).show()
                }
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                // Handle exceptions, such as network issues
                Toast.makeText(
                    this@MainActivity,
                    "Error fetching data: ${e.localizedMessage}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

ในฟังก์ชัน fetchUsers() เราใช้ coroutine เพื่อเรียก API แบบอะซิงโครนัส หากการเรียก API สำเร็จ เราจะอัปเดต UI ด้วยข้อมูลที่ดึงมา มิฉะนั้น จะแสดงข้อความแสดงข้อผิดพลาด

การอัปเดต UI

หากต้องการแสดงข้อมูลที่ดึงมา ให้สร้าง RecyclerView และอะแดปเตอร์เพื่อจัดการรายชื่อผู้ใช้

1. เพิ่ม RecyclerView ในไฟล์เค้าโครง activity_main.xml ของคุณ:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:listitem="@layout/user_item" />

2. สร้างไฟล์ layout user_item.xml สำหรับรายการผู้ใช้คนเดียว:

<TextView
    android:id="@+id/userName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="18sp" />

3. สร้าง UserAdapter Class:

class UserAdapter(private val users: List<User>) :
    RecyclerView.Adapter<UserAdapter.UserViewHolder>() {

    class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val userName: TextView = itemView.findViewById(R.id.userName)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.user_item, parent, false)
        return UserViewHolder(view)
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        val user = users[position]
        holder.userName.text = user.name
    }

    override fun getItemCount(): Int {
        return users.size
    }
}

4. ใน MainActivity.kt ตั้งค่า RecyclerView และอะแดปเตอร์:

private lateinit var userAdapter: UserAdapter

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

    // Set up the RecyclerView
    recyclerView.layoutManager = LinearLayoutManager(this)
    userAdapter = UserAdapter(emptyList())
    recyclerView.adapter = userAdapter

    // Fetch users from the internet
    fetchUsers()
}

5. อัปเดต UI ด้วยข้อมูลที่ดึงมา:

withContext(Dispatchers.Main) {
    // Update UI with the retrieved data
    users?.let {
        userAdapter = UserAdapter(it)
        recyclerView.adapter = userAdapter
    }
}

เราได้เรียนรู้วิธีตั้งค่าโครงการสำหรับทำแอพ Android Studio ด้วย Kotlin เพื่อดึงข้อมูลจากอินเทอร์เน็ตโดยใช้คำขอ HTTP เราใช้ Retrofit เพื่อจัดการกระบวนการและ Moshi สำหรับการแยกวิเคราะห์ JSON ความรู้นี้สามารถนำไปใช้ในการรับทำแอพที่ซับซ้อนและขับเคลื่อนด้วยข้อมูลสำหรับทำแอพ Android

เขียนแอพ Android Studio

ตอนที่ 9 Android Studio Kotlin การทำงานกับฐานข้อมูล SQLite