Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android java.lang.ClassCastException:kotlinx.coroutines.CompletableDeferedImpl不能强制转换为java.util.List?_Android_Kotlin_Viewmodel_Classcastexception_Kotlin Coroutines - Fatal编程技术网

Android java.lang.ClassCastException:kotlinx.coroutines.CompletableDeferedImpl不能强制转换为java.util.List?

Android java.lang.ClassCastException:kotlinx.coroutines.CompletableDeferedImpl不能强制转换为java.util.List?,android,kotlin,viewmodel,classcastexception,kotlin-coroutines,Android,Kotlin,Viewmodel,Classcastexception,Kotlin Coroutines,我正在开发一个新的android应用程序,但我得到了以下例外 java.lang.ClassCastException: kotlinx.coroutines.CompletableDeferredImpl cannot be cast to java.util.List at yodgorbek.komilov.musobaqayangiliklari.viewmodel.MainViewModel$loadNews$1.invokeSuspend(MainViewModel.kt:4

我正在开发一个新的android应用程序,但我得到了以下例外

java.lang.ClassCastException: kotlinx.coroutines.CompletableDeferredImpl cannot be cast to java.util.List
    at yodgorbek.komilov.musobaqayangiliklari.viewmodel.MainViewModel$loadNews$1.invokeSuspend(MainViewModel.kt:42)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6820)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:922)
在我的MainViewModel.kt中

@Suppress("UNCHECKED_CAST")
class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()
    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    val showLoading = MutableLiveData<Boolean>()
    val sportList = MutableLiveData <List<Article>>()
    val showError = SingleLiveEvent<String>()

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result = withContext(Dispatchers.IO) {
                newsRepository?.getNewsList()
            }
            // Hide progressBar once the operation is done on the MAIN (default) thread
            showLoading.value = false
            when (result) {

                is UseCaseResult.Success<*> -> {
                    sportList.value = result.data as List<Article>
                }
                is Error -> showError.value = result.message
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        // Clear our job when the linked activity is destroyed to avoid memory leaks
        job.cancel()
    }
}
在我的MainViewModel.kt下面

@Suppress("UNCHECKED_CAST")
class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    val job = Job()
    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    val showLoading = MutableLiveData<Boolean>()
    val sportList = MutableLiveData <List<Article>>()
    val showError = SingleLiveEvent<String>()

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result = withContext(Dispatchers.IO) {
                newsRepository?.getNewsList()
            }
            // Hide progressBar once the operation is done on the MAIN (default) thread
            showLoading.value = false
            when (result) {

                is UseCaseResult.Success<*> -> {
                    sportList.value = result.data as List<Article>
                }
                is Error -> showError.value = result.message
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        // Clear our job when the linked activity is destroyed to avoid memory leaks
        job.cancel()
    }
}
下面是SportNewsResponse.kt

数据类SportNewsResponse( val文章:列表, val状态:字符串, val totalResults:Int )

下面是UseCaseResult.kt

sealed class UseCaseResult<out T : Any>() {
    class Success<out T : Any>(val data: T) : UseCaseResult<T>()
    class Error(val exception: Throwable) : UseCaseResult<Nothing>()
}
密封类UseCaseResult(){
类成功(val数据:T):UseCaseResult()
类错误(val异常:Throwable):UseCaseResult()
}
在NewsRepository.kt下面,我在其中实现了UserCaseResult

interface NewsRepository {
    // Suspend is used to await 
    suspend fun getNewsList(): UseCaseResult<List<Article>>
}


@Suppress("UNCHECKED_CAST")
class NewsRepositoryImpl(private val sportsNewsApi: SportNewsInterface) : NewsRepository {
    override suspend fun getNewsList(): UseCaseResult<List<Article>> {

        return try {
            val result = sportsNewsApi.getNewsAsync()
            UseCaseResult.Success(result) as UseCaseResult<List<Article>>
        } catch (ex: Exception) {
            UseCaseResult.Error(ex)
        }
    }
}
接口新闻存储库{
//挂起用于等待
suspend fun getNewsList():UseCaseResult
}
@抑制(“未选中的_CAST”)
类NewsRepositoryImpl(私有val-SportNewsAPI:SportNewsInterface):新闻存储库{
重写getNewsList():UseCaseResult{
回击{
val result=sportsNewsApi.getNewsAsync()
UseCaseResult.Success(result)作为UseCaseResult
}捕获(例如:异常){
UseCaseResult.Error(ex)
}
}
}
在我的SportNewsInterface.kt下面

interface SportNewsInterface {

    @GET("v2/top-headlines?country=us&apiKey=da331087e3f3462bb534b3b0917cbee9")
     fun getNewsAsync(): Deferred<SportNewsResponse>

    @GET("/v2/top-headlines?sources=espn&apiKey=da331087e3f3462bb534b3b0917cbee9")
    fun getEspn(): Deferred<List<SportNewsResponse>>

    @GET("/v2/top-headlines?sources=football-italia&apiKey=da331087e3f3462bb534b3b0917cbee9")
    fun getFootballItalia(): Deferred<List<SportNewsResponse>>

    @GET("/v2/top-headlines?sources=bbc-sport&apiKey=da331087e3f3462bb534b3b0917cbee9")
    fun getBBCSport(): Deferred<List<SportNewsResponse>>
界面SportNewsInterface{
@GET(“v2/头条新闻?国家/地区=us&apiKey=DA331087E3F3462BB534B334B03B0917CBEE9”)
fun getNewsAsync():延迟
@GET(“/v2/头条新闻?来源=espn&apiKey=DA331087E3F3462BB534B034B0917CBEE9”)
fun getEspn():延迟
@GET(“/v2/头条新闻?来源=意大利足球协会&阿皮基=DA331087E3F3462BB534B034B0917CBEE9”)
fun getFootballItalia():延迟
@获取(“/v2/头条新闻?来源=bbc sport&apiKey=da331087e3f3462bb534b3b0917cbee9”)
fun getBBCSport():延迟
下面是我的服务器响应

{
    "status": "ok",
    "totalResults": 38,
    "articles": [
        {
            "source": {
                "id": "cnbc",
                "name": "CNBC"
            },
            "author": "Holly Ellyatt",
            "title": "Russia is now not the only pressing issue that NATO has to deal with - CNBC",
            "description": "Heads of state and government are meeting in the U.K. this week for the 70th anniversary of the military alliance NATO.",
            "url": "https://www.cnbc.com/2019/12/02/nato-summit-alliance-has-more-pressing-issues-than-russia-now.html",
            "urlToImage": "https://image.cnbcfm.com/api/v1/image/106272467-1575218599700gettyimages-997112494.jpeg?v=1575218712",
            "publishedAt": "2019-12-02T07:39:00Z",
            "content": "US president Donald Trump is seen during his press conference at the 2018 NATO Summit in Brussels, Belgium on July 12, 2018.\r\nAs heads of state and government meet in the U.K. this week for the 70th anniversary of the military alliance NATO, discussions are l… [+8623 chars]"
        },
        {
            "source": {
                "id": null,
                "name": "Chron.com"
            },
            "author": "Aaron Wilson",
            "title": "Bill O'Brien gets game ball from Deshaun Watson after Texans' win over Patriots - Chron",
            "description": "In an emotional moment, Texans coach Bill O'Brien was presented with the game ball by quarterback Deshaun Watson following a pivotal win over the New England Patriots.",
            "url": "https://www.chron.com/sports/texans/article/Bill-O-Brien-Deshaun-Watson-Texans-Patriots-14874678.php",
            "urlToImage": "https://s.hdnux.com/photos/01/07/23/50/18692664/3/rawImage.jpg",
            "publishedAt": "2019-12-02T06:16:00Z",
            "content": "<ul><li>Houston Texans head coach Bill O'Brien on the sidelines during the fourth quarter of an NFL game against the New England Patriots at NRG Stadium Sunday, Dec. 1, 2019, in Houston.\r\nHouston Texans head coach Bill O'Brien on the sidelines during the four… [+1583 chars]"


        }
    ]
}
{
“状态”:“确定”,
“总体结果”:38,
“条款”:[
{
“来源”:{
“id”:“cnbc”,
“名称”:“CNBC”
},
“作者”:“Holly Ellyatt”,
“标题”:“俄罗斯现在不是北约必须处理的唯一紧迫问题——CNBC”,
“描述”:“国家元首和政府首脑将于本周在英国召开北约联盟第七十周年会议。”
“url”:”https://www.cnbc.com/2019/12/02/nato-summit-alliance-has-more-pressing-issues-than-russia-now.html",
“urlToImage”:https://image.cnbcfm.com/api/v1/image/106272467-1575218599700gettyimages-997112494.jpeg?v=1575218712",
“发布日期”:“2019-12-02T07:39:00Z”,
“内容”:“美国总统唐纳德·特朗普在2018年7月12日在比利时布鲁塞尔举行的2018次北约峰会上的新闻发布会上被看到。”国家元首和政府首脑们本周在英国召开了北约军事联盟第七十周年会议,讨论的是…[ + 8623个字符]。
},
{
“来源”:{
“id”:空,
“名称”:“Chron.com”
},
“作者”:“艾伦·威尔逊”,
“标题”:“德克萨斯人战胜爱国者后,比尔·奥布莱恩从德肖恩·沃森那里得到了一个游戏球——时间”,
“描述”:“在一个激动人心的时刻,德克萨斯州教练比尔·奥布莱恩在战胜新英格兰爱国者队后,被四分卫德肖恩·沃森送给了比赛用球。”,
“url”:”https://www.chron.com/sports/texans/article/Bill-O-Brien-Deshaun-Watson-Texans-Patriots-14874678.php",
“urlToImage”:https://s.hdnux.com/photos/01/07/23/50/18692664/3/rawImage.jpg",
“发布日期”:“2019-12-02T06:16:00Z”,
“内容”:“2019年12月1日,星期日,休斯顿NRG体育场,NFL与新英格兰爱国者队比赛的第四节,休斯顿得克萨斯州主教练比尔·奥布莱恩在休士顿场边。\r\n休斯顿得克萨斯州主教练比尔·奥布莱恩在四场比赛的场边……[+1583场比赛]”
}
]
}
val result=sportsNewsApi.getNewsAsync()
UseCaseResult.Success(result)作为UseCaseResult
该强制转换非常可疑,因为即使没有它也可以工作。这意味着您的强制转换无效,导致您看到的错误。

不正确:

val result = sportsNewsApi.getNewsAsync()
正确:

val result = sportsNewsApi.getNewsAsync().await()

所以你已经做了一些改变 现在getNewsAsync必须返回UseCaseResult,而不是它的列表,因为这是端点返回的内容。
然后,您可以在
NewsRepository
在这两行中

 val result = sportsNewsApi.getNewsAsync()
 UseCaseResult.Success(result) as UseCaseResult<List<Article>>
或者,如果要获取该值,请使用
getNewsAsync()
上的
.await()
,如下所示

val result = sportsNewsApi.getNewsAsync().await()
 UseCaseResult.Success(result) as UseCaseResult<SportNewsResponse>
val result=sportsNewsApi.getNewsAsync().await()
UseCaseResult.Success(result)作为UseCaseResult

不要忘记现在您应该将结果强制转换为
usecasesult
,并删除
Deferred

的输出:
result.data.await()::class
?异常sameI仍然非常怀疑这一点。可能您仍在强制转换到错误的类型,但您尝试强制转换的对象已更改。您应该共享新的堆栈跟踪。java.lang.ClassCastException:yodgorbek.komilov.musobaqayangiliklari.internet.SportNewsResponse无法强制转换到yodgorbek.komi上的java.util.Listlov.musobaqayangiliklari.viewmodel.MainViewModel$loadNews$1.invokeSuspend(MainViewModel.kt:43)位于kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)我遇到上述异常我不明白我做错了什么好吧,你看,现在你得到的是
SportNewsResponse
,但假装它是
列表
。现在调用一个获取文章列表的方法。也许
result.getArticles()
。我不明白你的确切意思
getNewsAsync()
不返回
列表
,因此代码不正确。如果不指定
getNewsAsync()
实际返回的内容,则无法给出正确的实现。它返回SportNewsResponse结束点我现在将添加到代码中我已添加了所有必要的文件请检查它您认为主要的p是什么
UseCaseResult.Success(result) as UseCaseResult<Deferred<SportNewsResponse>>
val result = sportsNewsApi.getNewsAsync().await()
 UseCaseResult.Success(result) as UseCaseResult<SportNewsResponse>