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

Android Kotlin项目出现Kotlin.Unit错误的原因及修复方案

问题分析与解决步骤

1. 修复日志输出的Kotlin.Unit错误

你看到的Kotlin.Unit错误是因为err.printStackTrace()返回的是Unit类型,调用toString()后只会输出这个无意义的字符串,根本看不到真实的异常信息。把日志代码改成下面的写法,才能打印完整的错误栈:

catch (err: Exception) {
    Log.e("refreshPictureOfDay", "加载每日图片失败", err)
}

2. 解决图片无法加载的核心问题

问题点1:LiveData空安全处理

pictureOfDay是LiveData<PictureOfDay>,初始状态下它的值是null,在Data Binding中直接访问url会触发空指针异常。必须加上空安全操作符:

app:imageUrl="@{viewModel.pictureOfDay?.url}"

问题点2:过滤非图片类型的返回数据

NASA的每日天文图(APOD)可能返回视频类型(media_type为video),此时url是视频链接,Picasso无法加载视频,只会显示错误占位图。修改请求方法,只处理图片类型的数据:

private suspend fun refreshPictureOfDay() {
    withContext(Dispatchers.IO) {
        try {
            val result = NasaApi.retrofitService.getPictureOfTheDay()
            if (result.mediaType == "image") {
                _pictureOfDay.postValue(result)
            } else {
                Log.w("refreshPictureOfDay", "返回内容为视频,跳过图片加载")
                // 可选:设置一张默认图片占位
                _pictureOfDay.postValue(PictureOfDay("image", "视频内容", "你的默认图片本地路径或URL"))
            }
        } catch (err: Exception) {
            Log.e("refreshPictureOfDay", "加载每日图片失败", err)
        }
    }
}

问题点3:BindingAdapter空值显式处理

当url为null时,显式设置占位图,避免Picasso做无效加载:

@BindingAdapter("imageUrl")
fun bindImage(imageView: ImageView, url: String?) {
    url?.let {
        Picasso.with(imageView.context)
            .load(it)
            .placeholder(R.drawable.placeholder_picture_of_day)
            .error(R.drawable.placeholder_picture_of_day)
            .into(imageView)
    } ?: run {
        imageView.setImageResource(R.drawable.placeholder_picture_of_day)
    }
}

问题点4:确认Data Binding配置正确

确保布局文件和代码中正确绑定ViewModel并设置生命周期所有者:

  1. 布局根标签使用layout,声明ViewModel变量:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="viewModel"
            type="你的ViewModel完整类名"/>
    </data>
    <!-- 你的布局内容 -->
</layout>
  1. 在Activity/Fragment中绑定ViewModel:
val viewModel = ViewModelProvider(this)[YourViewModel::class.java]
val binding = DataBindingUtil.setContentView<YourLayoutBinding>(this, R.layout.your_layout)
binding.viewModel = viewModel
binding.lifecycleOwner = this // 必须设置,LiveData才能自动更新UI

3. 额外排查步骤

  • 检查Retrofit的BaseUrl是否为https://api.nasa.gov/,确认API_KEY已正确添加到请求参数中
  • 打印result.url,复制到浏览器中打开,验证是否为有效的图片链接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:51:34