如何在Jetpack compose中通过GET Request对多个参数进行改造来获取呼吸数据



这些天我正在为初学者开发一款英语学习应用程序所以我有问题,我想用两个参数(级别和单位(获取响应数据从数据库,如php代码中所示,通过改造类似于此,

https://adeega.xisaabso.online/Api/Article_vocabulary.php?Level=1&单位=1

那么我该怎么做呢?我需要帮助吗?下面是我的代码

Vocabulay_Api.kt

const val Vocabulary = "https://adeega.xisaabso.online/Api/"
interface getVocabularies {
@GET("Article_vocabulary.php")
fun getVocabularies(): Call<Vocabularies>
}
object getVocabulariesInstance {
val getVocabulariesSections: getVocabularies
init {
val retrofit = Retrofit.Builder()
.baseUrl(Vocabulary)
.addConverterFactory(GsonConverterFactory.create())
.build()
getVocabulariesSections = retrofit.create(getVocabularies::class.java)
}
}

词汇.kt

val users = getVocabulariesInstance.getVocabulariesSections.getVocabularies()
val data = remember { mutableStateOf(Vocabularies()) }
users.enqueue(object: Callback<Vocabularies> {
override fun onResponse(
call: Call<Vocabularies>,
response: Response<Vocabularies>
) {
val userData = response.body()
if(userData != null) {
data.value = userData
}
}
override fun onFailure(call: Call<Vocabularies>, t: Throwable) {
Toast.makeText(context, t.toString(), Toast.LENGTH_SHORT).show()
}
})

LazyColumn(
contentPadding = PaddingValues(
horizontal = 12.dp,
/*vertical = 0.dp*/
),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(data.value) { item ->
Cards_Vocabulary(data = item, navController)
//Divider(color = Color.Gray, thickness = 1.dp)
}
} // END LazyColumn

database.php

if(!empty($_GET['Level']) && !empty($_GET['Unit'])) {
$Level = (int)$_GET['Level'];
$Unit  = (int)$_GET['Unit'];

$Article = $pdo->prepare("SELECT * FROM App_vocabularies 
WHERE LevelID = ? AND UnitID = ?");
$Article->bindParam(1, $Level);
$Article->bindParam(2, $Unit);
$Article->execute();
$Article = $Article->fetchAll(PDO::FETCH_OBJ);
echo json_encode($Article);
}

如果您想知道如何将参数作为queryString传递给查询,下面是的操作

interface getVocabularies {
@GET("Article_vocabulary.php")
fun getVocabularies(@Query("Level") level: Int, @Query("Unit") unit: Int): Call<Vocabularies>
}

词汇.kt

getVocabulariesInstance.getVocabulariesSections.getVocabularies(aLevel, anUnit)

或者,如果你想避免多个功能参数并同时通过

interface getVocabularies {
@GET("Article_vocabulary.php")
fun getVocabularies(@QueryMap queries: Map<String, String>): Call<Vocabularies>
}

词汇.kt

val params : MutableMap<String, String> = mutableMapOf()
params["Level"] = aLevel
params["Unit"] = anUnit
getVocabulariesInstance.getVocabulariesSections.getVocabularies(params.toImmutableMap())

最新更新