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

Android Studio中java.lang.IllegalStateException报错,求修复Kotlin动物音效代码

解决Retrofit解析错误:java.lang.IllegalStateException: Begin object but was begin array

错误核心原因

你的Retrofit接口声明返回单个animalsound对象,但实际API返回的是JSON数组格式,导致解析器预期解析对象却收到数组,触发匹配异常。

具体修复步骤

1. 修改Retrofit接口定义

将接口返回类型从单个对象改为列表:

interface ApiInterface {
    // 根据实际接口路径修改@GET参数
    @GET("your-animal-sound-endpoint")
    fun getanimalsound(): Call<List<animalsound>>
}

2. 调整回调处理逻辑

同步修改回调泛型为列表类型,并处理数组中的数据:

binding.animalsoundimg.setOnClickListener {
    val call2 = apiinterface.getanimalsound()
    call2.enqueue(object : Callback<List<animalsound>> {
        override fun onResponse(
            call: Call<List<animalsound>>,
            response: Response<List<animalsound>>
        ) {
            if (response.isSuccessful) {
                val soundList = response.body()
                // 示例:取数组第一个元素的音效地址,可根据需求调整逻辑
                val soundUrl = soundList?.firstOrNull()?.soundurl
                soundUrl?.let { PlayAnimalSound(it) }
                // 额外处理空数组情况
                if (soundList.isNullOrEmpty()) {
                    Toast.makeText(applicationContext, "暂无可用音效", Toast.LENGTH_SHORT).show()
                }
            }
        }

        override fun onFailure(call: Call<List<animalsound>>, t: Throwable) {
            Toast.makeText(applicationContext, "Error: ${t.message}", Toast.LENGTH_SHORT).show()
        }
    })
}

3. 优化MediaPlayer使用(可选)

避免主线程阻塞,改用异步加载:

private fun PlayAnimalSound(soundurl: String) {
    mediaPlayer?.release() // 释放旧实例,防止内存泄漏
    mediaPlayer = MediaPlayer().apply {
        setDataSource(soundurl)
        prepareAsync() // 异步准备,不阻塞UI
        setOnPreparedListener { start() }
        setOnErrorListener { _, _, _ ->
            Toast.makeText(applicationContext, "音效加载失败", Toast.LENGTH_SHORT).show()
            true
        }
    }
}

验证建议

先通过Postman等工具确认API返回的JSON格式:

  • 数组格式示例:[{"soundurl":"https://xxx.com/sound.mp3"}, ...]
  • 对象格式示例:{"soundurl":"https://xxx.com/sound.mp3"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:25:04