本文介绍了我无法在recyclerview中显示类型不匹配的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my app I am successfully retrieving data from the server, I check data using logcat, it's fine, it's coming from the server. But I can't show this data in recyclerview because of Type mismatch issue. I am using retrofit in the MVVM pattern.

为了更好地理解,请参见下面的代码

for better understanding, see the code below

GetApi.kt

GetApi.kt

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

ApiClient.kt

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

Repository.kt

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

ArticleViewModel.kt

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

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

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

NewsData.kt

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

Article.kt

Article.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
)

Source.kt

Source.kt

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

我可以从服务器检索数据,但是不能在recyclerview中显示它Logcat结果

I can retrieve data from the server, but can't show it in recyclerviewLogcat result

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

How can show this data in recyclerview?

推荐答案

  • 您不是将List发送到setData,而是发送Response< List> ;,无论Response类是什么,都将发送其内部的值而不是其本身.

    • You are not sending List to setData, instead, you are sending Response<List>, whatever the Response class is, send the value inside it not itself.

      在GetApi中,它是Response< List>.而它是存储库中的Response,请修复返回类型

      In GetApi it is Response<List> whereas it is Response in repository, fix the return types

      将其更改为

      @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>
      

      这篇关于我无法在recyclerview中显示类型不匹配的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 15:09