kotlin 编写应用程序在启动后不加载API数据

lstz6jyr  于 2022-11-25  发布在  Kotlin
关注(0)|答案(1)|浏览(141)

我正在用Jetpack Compose创建一个精灵宝可梦应用程序。我正在用两部智能手机测试它:小米11 T Pro(安卓12)和小米8 Lite(安卓10)。
嗯,当我在小米8 Lite中启动应用程序时,它能正确启动,口袋妖怪列表也能完美加载。但当我在小米11 T Pro中启动应用程序时,它却无法加载,什么都没有显示。我发现了两件事:
1.如果我打开布局检查器,它会立即加载,而不做任何其他事情...
1.当屏幕是空的(刚刚启动后,加载前),如果我点击1-2次屏幕上它开始发送请求和加载正确。
为什么会这样?
我附加了ViewModel和MainActivity。
PokemonListViewModel.kt

@HiltViewModel
class PokemonListViewModel @Inject constructor(
    private val repository: PokemonRepositoryImpl
) : ViewModel() {

    private var currentPage = 0

    var pokemonList = mutableStateOf<List<PokedexListEntry>>(listOf())
    var loadError = mutableStateOf("")
    var isLoading = mutableStateOf(false)
    var endReached = mutableStateOf(false)

    private var cachedPokemonList = listOf<PokedexListEntry>()
    private var isSearchStarting = true
    var isSearching = mutableStateOf(false)

    init {
        loadPokemonList()
    }

    // TODO: Search online, not only already loaded pokémon
    fun searchPokemonList(query: String) {
        val listToSearch = if (isSearchStarting) {
            pokemonList.value
        } else {
            // If we typed at least one character
            cachedPokemonList
        }
        viewModelScope.launch(Dispatchers.Default) {
            if (query.isEmpty()) {
                pokemonList.value = cachedPokemonList
                isSearching.value = false
                isSearchStarting = true
                return@launch
            }

            val results = listToSearch.filter {
                // Search by name or pokédex number
                it.pokemonName.contains(query.trim(), true) ||
                        it.number.toString() == query.trim()
            }

            if (isSearchStarting) {
                cachedPokemonList = pokemonList.value
                isSearchStarting = false
            }

            // Update entries with the results
            pokemonList.value = results
            isSearching.value = true
        }
    }

    fun loadPokemonList() {
        viewModelScope.launch {
            isLoading.value = true

            val result = repository.getPokemonList(PAGE_SIZE, currentPage * PAGE_SIZE)
            when (result) {
                is Resource.Success -> {
                    endReached.value = currentPage * PAGE_SIZE >= result.data!!.count

                    val pokedexEntries = result.data.results.mapIndexed { index, entry ->
                        val number = getPokedexNumber(entry)
                        val url = getImageUrl(number)
                        PokedexListEntry(
                            entry.name.replaceFirstChar(Char::titlecase),
                            url,
                            number.toInt()
                        )
                    }

                    currentPage++

                    loadError.value = ""
                    isLoading.value = false
                    pokemonList.value += pokedexEntries
                }
                is Resource.Error -> {
                    loadError.value = result.message!!
                    isLoading.value = false
                }
                is Resource.Loading -> {
                    isLoading.value = true
                }
            }

        }
    }

    private fun getImageUrl(number: String): String {
        return "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${number}.png"
    }

    private fun getPokedexNumber(entry: Result): String {
        return if (entry.url.endsWith("/")) {
            entry.url.dropLast(1).takeLastWhile { it.isDigit() }
        } else {
            entry.url.takeLastWhile { it.isDigit() }
        }
    }

}

MainActivity.kt

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val argPokemonName = "pokemonName"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposePokedexTheme {
                val navController = rememberNavController()
                NavHost(navController = navController, startDestination = "pokemon_list_screen") {
                    composable("pokemon_list_screen") {
                        PokemonListScreen(navController = navController)
                    }
                    composable(
                        "pokemon_detail_screen/{$argPokemonName}",
                        arguments = listOf(
                            navArgument(argPokemonName) {
                                type = NavType.StringType
                            }
                        )
                    ) {
                        val pokemonName = remember {
                            it.arguments?.getString(argPokemonName)
                        }
                        PokemonDetailScreen(
                            pokemonName = pokemonName?.lowercase(Locale.ROOT) ?: "",
                            navController = navController
                        )
                    }
                }
            }
        }
    }

}

如果有人知道为什么它不加载...我怀疑可能是init { }或Hilt注入正在做一些事情,使init不启动或什么。
感谢您的时间和帮助!

kfgdxczn

kfgdxczn1#

好吧,这似乎是一个小米报告的错误,谷歌不会修复,你可以在这里看到它:https://issuetracker.google.com/issues/227926002
它对我起作用了,在设置内容之前添加了一点延迟,它似乎起作用了:
生命周期范围。启动{延迟(300)设置内容{ JetpackComposePokedexTheme {...} } }
还可以看到:编写NavHost启动白色屏幕

相关问题