您現在的位置是:首頁 > 棋牌
Android Jetpack Compose API 教程
- 由 skysevenqi 發表于 棋牌
- 2022-11-10
halt on怎麼設定
每日分享最新,最流行的軟體開發知識與最新行業趨勢,希望大家能夠一鍵三連,多多支援,跪求關注,點贊,留言。
在本教程中,我將展示如何使用 Android Jetpack Compose 向 API 傳送請求並顯示接收到的資料。
準備 API
首先,我們需要實際建立一個簡單的 API 來從中檢索資料。
對於本教程,我將使用“JSON 伺服器”:
https ://github。com/typicode/json-server
安裝非常簡單,您只需要開啟終端並執行以下命令:
npm install -g json-server
接下來我們需要建立一個“data。json”檔案並輸入一些資訊。隨意將值更改為您想要的任何值。
{
“users”: [
{
“id”: 1,
“profile”: {
“age”: 20,
“name”: “Ethan”,
“email”: “example@email。com”
}
}
]
}
最後,您可以透過以下命令啟動伺服器:
json-server ——host [Your Network IP] data。json
確保將主機更改為您的本地網路,需要定義網路,以便模擬器/實際裝置可以訪問它。
如果您訪問
http://ip:3000/users,您應該會在瀏覽器中看到以下資料。
JSON資料
建立專案
接下來,我們需要開啟 Android Studio 並建立將用於本教程的新專案。
當提示輸入要建立的專案型別時,選擇“Empty Compose Activity”
新作曲專案
接下來給它一個名稱,例如“ApiExample”,然後單擊完成。
這是我在建立專案後拍攝的影象,因此我的儲存位置通常是“ApiExample”。
新專案撰寫
編輯清單檔案
首先,我們需要編輯清單檔案,因為我們需要網際網路位置,因此在“應用程式”部分上方新增以下內容:
此外,我們不會使用安全協議,因此如果您不使用 https,請在應用程式中新增以下內容:
android:usesCleartextTraffic=“true”
確保關閉上述功能以進行生產。
安裝依賴項
接下來,我們需要安裝將用於該專案的依賴項。
開啟模組“build。gradle”並新增以下實現:
dependencies {
implementation ‘com。squareup。retrofit2:retrofit:2。9。0’
implementation ‘com。squareup。retrofit2:converter-gson:2。5。0’
}
同步專案以安裝依賴項。
建立使用者 API
接下來我們需要建立檔案來處理 API 呼叫,建立一個新的“api”包,然後建立一個名為“UserApi。kt”的檔案,然後用以下內容填充它:
package com。example。apiexample。api
import com。example。apiexample。ProfileModel
import com。example。apiexample。UserModel
import okhttp3。ResponseBody
import retrofit2。Call
import retrofit2。Response
import retrofit2。Retrofit
import retrofit2。http。Body
import retrofit2。http。GET
import retrofit2。http。Headers
import retrofit2。http。Path
public interface UserApi {
@Headers(
“Accept: application/json”
)
@GET(“users/{id}”)
abstract fun getUserById(@Path(“id”) id: String): Call
}
不要擔心金額的任何錯誤,因為它們將在以後修復。
此呼叫採用使用者 ID 並檢索該使用者的個人資料。
編輯 MainActivity
接下來我們需要編輯 MainActivity。kt 檔案,首先我們將定義匯入:
package com。example。apiexample
import android。content。Context
import android。os。Bundle
import android。util。Log
import android。view。View
import android。widget。Toast
import androidx。activity。ComponentActivity
import androidx。activity。compose。setContent
import androidx。compose。foundation。layout。*
import androidx。compose。material。*
import androidx。compose。runtime。Composable
import androidx。compose。runtime。MutableState
import androidx。compose。runtime。mutableStateOf
import androidx。compose。runtime。remember
import androidx。compose。ui。Alignment
import androidx。compose。ui。Modifier
import androidx。compose。ui。graphics。Color
import androidx。compose。ui。text。TextStyle
import androidx。compose。ui。text。font。FontFamily
import androidx。compose。ui。text。input。TextFieldValue
import androidx。compose。ui。text。style。TextAlign
import androidx。compose。ui。tooling。preview。Preview
import androidx。compose。ui。unit。dp
import androidx。compose。ui。unit。sp
import com。example。apiexample。api。UserApi
import com。example。apiexample。ui。theme。ApiExampleTheme
import com。example。apiexample。ui。theme。Purple700
import retrofit2。*
import retrofit2。converter。gson。GsonConverterFactory
接下來我們需要將 MainActivity 類更改為以下內容:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super。onCreate(savedInstanceState)
setContent {
ApiExampleTheme {
// A surface container using the ‘background’ color from the theme
Surface(
modifier = Modifier。fillMaxSize(),
color = MaterialTheme。colors。background
) {
MainScreen()
}
}
}
}
}
沒有什麼太複雜了。
接下來,我們需要使用與我們之前建立的 JSON 資料檔案相同的變數來建立資料類。
data class ProfileModel(
var age: String,
var name: String,
var email: String,
)
data class UserModel(
var profile: ProfileModel
)
接下來我們需要建立 MainScreen Composable,如果您不太熟悉 UI,請隨時檢視我的 Compose 表單教程:
https ://dev。to/ethand91/android-jetpack-compose-form-tutorial- 279a
@Composable
fun MainScreen() {
Scaffold(
topBar = {
TopAppBar(
backgroundColor = Purple700,
title = {
Text(
text = “Simple API Request”,
modifier = Modifier。fillMaxWidth(),
textAlign = TextAlign。Center,
color = Color。White
)
}
)
},
content = {
Column(
modifier = Modifier。fillMaxWidth(),
verticalArrangement = Arrangement。Center,
horizontalAlignment = Alignment。CenterHorizontally
) {
val id = remember {
mutableStateOf(TextFieldValue())
}
val profile = remember {
mutableStateOf(ProfileModel(
age = “”,
name = “”,
email = “”
))
}
Text(
text=“API Sample”,
style= TextStyle(
fontSize = 40。sp,
fontFamily = FontFamily。Cursive
)
)
Spacer(modifier = Modifier。height(15。dp))
TextField(
label = { Text(text = “User ID”)},
value = id。value,
onValueChange = { id。value = it }
)
Spacer(modifier = Modifier。height(15。dp))
Box(modifier = Modifier。padding(40。dp, 0。dp, 40。dp, 0。dp)) {
Button(
onClick = {
val data = sendRequest(
id = id。value。text,
profileState = profile
)
Log。d(“Main Activity”, profile。toString())
}
) {
Text(text = “Get Data”)
}
}
Spacer(modifier = Modifier。height(15。dp))
Text(text = profile。component1()。toString(), fontSize = 40。sp)
}
}
)
}
這將建立一個包含標題、文字輸入和按鈕的簡單表單。最後,我們需要建立一個函式來實際呼叫 API,獲取資料並將其顯示給使用者。確保將 IP 地址替換為您自己的 IP 地址。
fun sendRequest(
id: String,
profileState: MutableState
) {
val retrofit = Retrofit。Builder()
。baseUrl(“http://192。168。0。109:3000”)
。addConverterFactory(GsonConverterFactory。create())
。build()
val api = retrofit。create(UserApi::class。java)
val call: Call
call!!。enqueue(object: Callback
override fun onResponse(call: Call
if(response。isSuccessful) {
Log。d(“Main”, “success!” + response。body()。toString())
profileState。value = response。body()!!。profile
}
}
override fun onFailure(call: Call
Log。e(“Main”, “Failed mate ” + t。message。toString())
}
})
}
全部完成!現在我們終於可以試一試了!
執行應用程式
最後,我們可以在模擬器/實際裝置上執行示例應用程式,一旦應用程式啟動,您應該會看到以下螢幕:
模擬器初始狀態
接下來,透過在輸入文字中輸入他們的 id 來輸入您想要獲取的個人資料的使用者。由於我只有一個使用者,我輸入 1。
完成後,單擊“獲取資料”按鈕,底部文字應顯示使用者的個人資料資訊。
收到模擬器資料
全部完成!
結論
在本教程中,我展示瞭如何使用 Android Jetpack Compose 呼叫一個簡單的 API 來檢索和顯示資訊。
我希望它對您有所幫助,請隨時嘗試使用真實的 API 和/或更改 UI 等進行試驗。
該專案的完整原始碼可以在這裡找到:
https ://github。com/ethand91/compose-api-tutorial
上一篇:花灑套裝怎麼安裝?