【问题标题】:I can't show data in recyclerview for type mismatch我无法在 recyclerview 中显示类型不匹配的数据
【发布时间】:2021-03-30 07:52:32
【问题描述】:

在我的应用程序中,我成功地从服务器检索数据,我使用 logcat 检查数据,很好,它来自服务器。但由于类型不匹配问题,我无法在 recyclerview 中显示此数据。我在 MVVM 模式中使用改造。

为了更好的理解,请看下面的代码

GetApi.kt

@GET("v2/top-headlines?country=us")
suspend fun getNews(
    @Query("apiKey") apikey: String
):Response<List<NewsData>>

ApiClient.kt

private val retrofit2 by lazy {
    Retrofit.Builder()
        .baseUrl(NEWS_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

val newsApi: GetApi by lazy {
    retrofit2.create(GetApi::class.java)
}

Repository.kt

suspend fun getNews(apiKey: String):Response<List<NewsData>> {
    return ApiClient.newsApi.getNews(apiKey)
}

ArticleViewModel.kt

class ArticleActivityViewModel(private val repository: Repository): ViewModel() {
val newsResponse: MutableLiveData<Response<List<NewsData>>> = MutableLiveData()

fun getNews(apiKey: String){
    viewModelScope.launch {
        val n = repository.getNews(apiKey)
        newsResponse.value = n
    }
  }
 }

ArticleActivity.kt

viewModel.getNews(NEWS_APP_ID)
    viewModel.newsResponse.observe(this, Observer { response ->
        if (response.isSuccessful){
            articleAdapter.setData(response)
        }else{
            Log.d("Response", response.errorBody().toString())
        }
    })

ArticleAdapter.kt

class ArticleAdapter (private val onItemClickListener: OnItemClickListener): RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {
private var articleList = emptyList<NewsData>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.article_row, parent, false)
    return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemView.article_headline.text = articleList[position].articles[position].title
    holder.itemView.article_author.text = articleList[position].articles[position].author
    holder.itemView.article_date.text = articleList[position].articles[position].publishedAt
    Glide.with(holder.itemView.context).load(articleList[position].articles[position].urlToImage).into(holder.itemView.article_image)

    holder.itemView.setOnClickListener {
        onItemClickListener.onClick(articleList[position],position)
    }

}
override fun getItemCount(): Int {
    return articleList.size
}

fun setData(newList: List<NewsData>) {
    notifyDataSetChanged()
    articleList = newList
    notifyDataSetChanged()
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}

NewsData.kt

data class NewsData(
@SerializedName("articles")
val articles: List<Article>,
@SerializedName("status")
val status: String,
@SerializedName("totalResults")
val totalResults: Int
)

文章.kt

data class Article(
@SerializedName("author")
val author: String,
@SerializedName("content")
val content: String,
@SerializedName("description")
val description: String,
@SerializedName("publishedAt")
val publishedAt: String,
@SerializedName("source")
val source: Source,
@SerializedName("title")
val title: String,
@SerializedName("url")
val url: String,
@SerializedName("urlToImage")
val urlToImage: String
)

来源.kt

data class Source(
@SerializedName("id")
val id: String,
@SerializedName("name")
val name: String
)

我可以从服务器检索数据,但无法在 recyclerview 中显示 日志猫结果

如何在 recyclerview 中显示这些数据?

【问题讨论】:

  • fun setData(newList: List) { articleList = newList notifyDataSetChanged() }
  • 您不是将 List 发送到 setData,而是发送 Response>,无论 Response 类是什么,发送它内部的值而不是它本身。
  • 你也有误会,在 GetApi 中它是 Response> 而它是 Response 在存储库中,修复返回类型。
  • 我已经更新了我的问题代码,但我无法在 recyclerview bkz 中显示列表,这是 retuen 响应
  • 确保您已成功检索数据。

标签: android kotlin mvvm android-recyclerview retrofit2


【解决方案1】:
  • 您不是将 List 发送到 setData,而是发送 Response,无论 Response 类是什么,都发送其中的值而不是其本身。

  • 在 GetApi 中是 Response 而在存储库中是 Response,修复返回类型

改成

@GET("v2/top-headlines?country=us")
suspend fun getNews(
    @Query("apiKey") apikey: String
):Response<List<NewsData>>

而不是

@GET("v2/top-headlines?country=us")
suspend fun getNews(
    @Query("apiKey") apikey: String
):Response<NewsData>

【讨论】:

  • 我试过回答,但现在它显示另一个问题,错误是 java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
  • 我会根据您的建议更新我的代码
  • 请提供NewsData的数据类
【解决方案2】:

如上所述,您不是在发送列表,而是在发送响应。将返回类型从 Response> 更改为 List

像这样:

    @GET("v2/top-headlines?country=us")
    suspend fun getNews(@Query("apiKey") apikey: String):List<NewsData>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多