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

Android中Retrofit GET请求失效,Compose笑话列表无法展示求助

问题排查与修复方案

1. Joke数据类语法错误

原代码中val id: Int,.存在无效符号,会导致编译失败或Gson解析异常,修正后:

data class Joke(
    val id: Int,
    val punchline: String,
    val setup: String,
    val type: String
)

2. ViewModel列表未使用可观察状态

普通mutableListOf的变化无法触发Compose界面重组,必须替换为mutableStateListOf,让Compose感知列表更新:

class JokeViewModel : ViewModel() {
    private val _jokeList = mutableStateListOf<Joke>()
    var errorMessage by mutableStateOf("")
    val jokeList: List<Joke> get() = _jokeList

    fun getJokeList() {
        viewModelScope.launch {
            val apiService = JokeRepository.getInstance()
            try {
                _jokeList.clear()
                val joke = apiService.getJoke(1)
                _jokeList.add(joke)
            } catch (e: Exception) {
                errorMessage = e.message ?: "未知错误"
            }
        }
    }
}

3. Activity中ViewModel实例化方式错误

直接new ViewModel会导致配置变化(如屏幕旋转)时重建实例,且无法关联Compose生命周期,需改用viewModel()函数:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            HasyamTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    val jokeViewModel = viewModel<JokeViewModel>()
                    JokeView(jvm = jokeViewModel)
                }
            }
        }
    }
}

4. Retrofit接口参数类型优化

API的id为整数类型,接口参数改用Int更严谨,避免类型转换问题:

const val BASE_URL = "https://official-joke-api.appspot.com/"

interface JokeRepository {
    @GET("jokes/{id}")
    suspend fun getJoke(@Path("id") id: Int) : Joke

    companion object {
        var apiService: JokeRepository? = null
        fun getInstance(): JokeRepository {
            if (apiService == null) {
                apiService = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build().create(JokeRepository::class.java)
            }
            return apiService!!
        }
    }
}

5. Card组件重复设置点击事件

Card已提供onClick参数,同时添加.clickable {}会导致点击事件冲突,需移除修饰符中的重复设置:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun JokeComponent(joke: Joke) {
    var opened by remember { mutableStateOf(false)}

    Column(
        modifier = Modifier.padding(15.dp)
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            elevation = CardDefaults.cardElevation(
                defaultElevation = 5.dp
            ),
            onClick = { opened = !opened }
        ) {
            Text(modifier = Modifier.padding(15.dp), text = joke.setup)
        }

        if (opened) {
            Text(modifier = Modifier.padding(15.dp), text = joke.punchline)
        }
    }
}

额外依赖检查

确保在模块级build.gradle中添加必要依赖:

dependencies {
    // Retrofit相关
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    // ViewModel Compose支持
    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2'
    // 其他Jetpack Compose基础依赖...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:05:18