- build.gradle (Module: app)
- สำรวจ API ของ Github
- สร้าง class
- สร้าง API interface
- สร้าง TextView ไว้แสดงผล
- MainActivity
- ขอสิทธิ์
สร้างโปรเจ็กส์ชื่อ RetrofitDemo ภาษา Kotlin เพื่ออ่าน API ของ Github
1.build.gradle (Module: app)
dependencies { ... implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' }
2.สำรวจ API ของ Github
API ของ Github https://api.github.com/search/users?q=rokano
{ "total_count": 7, "incomplete_results": false, "items": [ { "login": "rokanost", "id": 5094636, "node_id": "MDQ6VXNlcjUwOTQ2MzY=", "avatar_url": "https://avatars0.githubusercontent.com/u/5094636?v=4", "gravatar_id": "", "url": "https://api.github.com/users/rokanost", "html_url": "https://github.com/rokanost", "followers_url": "https://api.github.com/users/rokanost/followers", "following_url": "https://api.github.com/users/rokanost/following{/other_user}", "gists_url": "https://api.github.com/users/rokanost/gists{/gist_id}", "starred_url": "https://api.github.com/users/rokanost/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/rokanost/subscriptions", "organizations_url": "https://api.github.com/users/rokanost/orgs", "repos_url": "https://api.github.com/users/rokanost/repos", "events_url": "https://api.github.com/users/rokanost/events{/privacy}", "received_events_url": "https://api.github.com/users/rokanost/received_events", "type": "User", "site_admin": false, "score": 32.160065 }, { ...} .... ] }
3.สร้าง class
ไฟล์ Users.kt
package com.phaisarn.retrofitdemo class Users { var id: Int = 0 var login: String = "" var score: Float = 0.0f }
ไฟล์ UsersList.kt
package com.phaisarn.retrofitdemo import com.google.gson.annotations.SerializedName class UsersList { @SerializedName("items") var users: List<Users>? = null }
4.สร้าง API interface
ไฟล์ Api.java
package com.phaisarn.retrofitdemo; import retrofit2.Call; import retrofit2.http.GET; public interface Api { //urls @GET("users?q=rokano") Call<UsersList> getUsers(); }
5.สร้าง TextView ไว้แสดงผล
ไฟล์ main_activity.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" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/tv_users" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:scrollbars="vertical" android:text="Hello World!" android:textColor="@color/colorPrimaryDark" android:textSize="16sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.051" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.032"/> </androidx.constraintlayout.widget.ConstraintLayout>
6. MainActivity
ไฟล์ MainActivity.kt
package com.phaisarn.retrofitdemo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import android.util.Log import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { val BASE_URL = "https://api.github.com/search/" var tv_user: TextView? = null var str: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tv_user = findViewById(R.id.tv_users) getUsers() } // function to call server and update ui fun getUsers() { var retrofit: Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() var api = retrofit.create(Api::class.java) var call = api.users call.enqueue(object : Callback<UsersList> { override fun onResponse(call: Call<UsersList>?, response: Response<UsersList>?) { var usres = response?.body() var user = usres?.users var length = user!!.size for (i in 0 until length) { str = str + "\n" + user.get(i).id + " " + user.get(i).login } tv_user!!.text = str } override fun onFailure(call: Call<UsersList>?, t: Throwable?) { Log.v("Error", t.toString()) } }) } }
7.ขอสิทธิ์
ไฟล์ AndroidManifest.xml
<manifest> <uses-permission android:name="android.permission.INTERNET"/> .... </manifest>