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

AWS Query查询结果无法存入本地mutableList问题求助

问题原因与解决方案

问题根源

你遇到的是异步调用时序问题:

  • Amplify.DataStore.query 属于异步IO操作,你传入的成功/失败回调会在后台查询完成后才会执行
  • 你写在query方法后的Log.i("Testing2","$userContent")是同步执行的,执行顺序远早于查询回调,此时还没有任何数据被添加到userContent中,所以打印为空
  • 回调内的Testing1打印是查询完成、数据已经插入列表后才执行的,所以能看到完整数据

解决方案

  • 方案1:直接在回调中处理后续逻辑

    所有需要用到userContent的操作(比如UI更新、数据加工)都放到查询成功回调的while循环之后执行,如果涉及UI操作需要切换到Android主线程:
    var userContent : MutableList<MutableList<String>> = arrayListOf()
    Amplify.DataStore.query(UserInfo::class.java,
        Where.matches(UserInfo.USER.eq("$myID")),
        { posts ->
            while(posts.hasNext()){
                val post = posts.next()
                userContent.add(mutableListOf(post.content, post.username, post.password))
                Log.i("Testing1","$userContent")
            }
            // 所有需要用到userContent的逻辑都写在这里
            runOnUiThread {
                // 比如更新RecyclerView、更新TextView等UI操作
                Log.i("TestingAfterQuery","$userContent")
            }
        },
        { Log.e("Auth","Error",it) }
    )
    
  • 方案2:将回调转为协程挂起函数(推荐)

    如果项目中使用Kotlin协程,可以把回调式API封装为挂起函数,用同步写法实现异步逻辑,避免回调嵌套:
    // 封装挂起函数
    suspend fun queryUserInfoById(myID: String): List<MutableList<String>> = suspendCancellableCoroutine { cont ->
        val userContent = mutableListOf<MutableList<String>>()
        Amplify.DataStore.query(UserInfo::class.java,
            Where.matches(UserInfo.USER.eq(myID)),
            { posts ->
                while(posts.hasNext()){
                    val post = posts.next()
                    userContent.add(mutableListOf(post.content, post.username, post.password))
                }
                cont.resume(userContent)
            },
            { error ->
                cont.resumeWithException(error)
            }
        )
    }
    
    // 调用处示例(需要在协程作用域中执行)
    lifecycleScope.launch {
        try {
            val userContent = queryUserInfoById(myID)
            Log.i("TestingCoroutine","$userContent")
            // 后续处理逻辑
        } catch (e: Exception) {
            Log.e("Auth","查询失败",e)
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:06:03