You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Jetpack Compose安卓论坛APP通知发送报错:uid类型不匹配

问题描述

我正在使用Kotlin和Jetpack Compose开发一款安卓论坛APP,想要给特定帖子的回复者发送通知。首先通过getOthersToken方法获取他们的uid和token,再调用createNotification方法发送通知,但遍历thoseWhoRepliedEntity.uid时出现错误——此处的uid被识别为Char类型而非String类型。

错误原因

ThoseWhoRepliedEntity中的uid字段定义为String类型,但在Kotlin中,直接对String执行for (uid in thoseWhoRepliedEntity.uid)循环时,会将字符串拆解为单个Char进行遍历,导致循环内的uid变量类型变为Char,而NotificationEntity的构造参数需要String类型的uid,最终引发类型不匹配错误。

另外,每个ThoseWhoRepliedEntity对应一个回复者,本身就只包含一个uid,完全不需要遍历uid字符串。

修复方案
  1. 移除不必要的循环:直接使用thoseWhoRepliedEntity.uid完整字符串创建NotificationEntity,无需遍历
  2. 优化Service实例创建:避免在循环内重复创建NotificationService实例,提前初始化一次提升性能
优化后的完整代码
var thoseWhoReplied = mutableListOf<ThoseWhoRepliedEntity>()

// 提前初始化Service实例,避免重复创建
val userService: UserService = retrofit.create(UserService::class.java)
val notificationService: NotificationService = retrofit.create(NotificationService::class.java)

val apiResponse = userService.getOthersToken(token, postId)
    .execute().body() ?: throw IllegalStateException("body is null.")

for (info in apiResponse) {
    val thoseWhoRepliedEntity = ThoseWhoRepliedEntity(
        info.uid,
        info.token
    )
    thoseWhoReplied.add(thoseWhoRepliedEntity)

    try {
        // 直接使用完整的uid字符串,无需遍历
        val notification = NotificationEntity(
            thoseWhoRepliedEntity.uid,
            "You have a reply.",
            "${LocalDateTime.now()}"
        )

        notificationService.createNotification(token, notification)
            .enqueue(object : Callback<ResponseBody> {
                override fun onResponse(
                    call: Call<ResponseBody>,
                    response: Response<ResponseBody>
                ) {
                    Log.d("Response is", "${response.body()}")
                }

                override fun onFailure(
                    call: Call<ResponseBody>,
                    t: Throwable
                ) {
                    Log.d("Hi", "error: ${t.message}")
                }
            })
    } catch (e: Exception) {
        Log.e("Notification Error", "Failed to send notification", e)
    }
}
额外说明
  • 建议在onFailure中打印具体的异常信息(如${t.message}),方便排查问题
  • 添加全局的异常捕获,避免单个通知发送失败导致整个流程中断

内容的提问来源于stack exchange,提问作者Yuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:42:29