【问题标题】:why retrofit returning empty data?为什么要改造返回空数据?
【发布时间】:2020-05-13 19:47:18
【问题描述】:

我正在开发一个新的 android 应用程序,但我的应用程序在 MainActivity 的回收器视图中显示空数据,并且我放了一个断点,那里也显示 null,但我已经在初始化数据我想知道我在哪里犯错了失踪了吗?

在我的 RestClient.kt 下

class RestClient {

    internal val httpLoggingInterceptor: HttpLoggingInterceptor
        get() {
            val httpLoggingInterceptor = HttpLoggingInterceptor()
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            return httpLoggingInterceptor
        }


    internal fun getOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .build()
    }

    companion object {

        private val ROOT_URL = "http://www.mocky.io"

        /**
         * Get Retrofit Instance
         */
        private val retrofitInstance: Retrofit
            get() = Retrofit.Builder()
                .baseUrl(ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        /**
         * Get API Service
         *
         * @return API Service
         */
        val apiService: RestInterface
            get() = retrofitInstance.create(RestInterface::class.java)
    }

}

在我的 Post.kt 数据类下面

data class Post(
    @SerializedName("description")
    val description: String,
    @SerializedName("id")
    val id: Int,
    @SerializedName("image")
    val image: String,
    @SerializedName("published_at")
    val publishedAt: String,
    @SerializedName("title")
    val title: String,
    @SerializedName("user_id")
    val userId: Int
)

在 RestList.kt 下

data class RestList(
    @SerializedName("posts")
    val posts: List<Post>
)

在我的界面下方

interface RestInterface {
    @get:GET("/v2/59f2e79c2f0000ae29542931")
    val getPosts: Call<RestList>
}

在适配器下方

 class RestAdapter(val post: List<Post>?,val restList: RestList?) : RecyclerView.Adapter<RestAdapter.PostHolder>() {


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {
    val itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list, null)
    return PostHolder(itemView)
}

override fun getItemCount(): Int {
    return post?.size!!
}


override fun onBindViewHolder(holder: PostHolder, position: Int) {
    val posts = post?.get(position)
    Picasso
        .get() // give it the context
        .load(posts?.image) // load the image
        .into(holder.postImage)
    holder.userId.text = posts?.userId.toString()
    holder.postTitle.text = posts?.title
    holder.postTime.text = posts?.publishedAt
    holder.postDescription.text = posts?.description


}

class PostHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val postImage: ImageView
    val userId: TextView
    val postTitle: TextView
    val postTime: TextView
    val postDescription: TextView

    init {
        postImage = itemView.findViewById(R.id.postImage)
        userId = itemView.findViewById(R.id.userId)
        postTitle = itemView.findViewById(R.id.postTitle)
        postTime = itemView.findViewById(R.id.postTime)
        postDescription = itemView.findViewById(R.id.postDescription)
    }

}

}

我在mainactivity.kt下面调用改造

class MainActivity : AppCompatActivity() {

    companion object{
        const val  TAG = "internet"
    }

    private  var recyclerView: RecyclerView? = null
    private  var restAdapter: RestAdapter? = null
   private var restInterface: RestInterface? = null
    private var postList: List<Post>? = null
    private var restList: RestList? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.recycler_view)


        restInterface = RestClient.apiService
        val call = restInterface?.getPosts
        call?.enqueue(object : Callback<RestList> {
            override fun onResponse(call: Call<RestList>, response: Response<RestList>) {
                if (response.body() != null) {
                    restList = response.body()
                    val layoutManager = LinearLayoutManager(applicationContext)
                    recyclerView?.layoutManager = layoutManager

                    // initialize postList with posts
                    postList = restList?.posts
                    restAdapter = RestAdapter(postList, restList)

                    //this should be come later
                    recyclerView?.adapter = restAdapter
                }
            }


            override fun onFailure(call: Call<RestList>, t: Throwable) {
                Log.e(TAG, "There is no internet connection")
            }


        })
    }

}

在我的 activity_main.xml 下方

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>

在 post_list.xml 下方

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorWhite">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.55" />

    <ImageView
        android:id="@+id/postImage"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="16:9"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@id/guideline"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="ContentDescription" />

    <TextView
        android:id="@+id/userId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="25dp"
        android:layout_marginLeft="25dp"
        android:layout_marginTop="10dp"
        android:text="Placeholder"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/postTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Secondary"
        app:layout_constraintEnd_toStartOf="@id/postImage"
        app:layout_constraintStart_toStartOf="@id/userId"
        app:layout_constraintTop_toBottomOf="@id/userId" />

    <TextView
        android:id="@+id/postTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="10dp"
        android:text="Tertiary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="@id/userId"
        app:layout_constraintTop_toBottomOf="@id/postTitle" />

    <TextView
        android:id="@+id/postDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="10dp"
        android:text="Tertiary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="@id/userId"
        app:layout_constraintTop_toBottomOf="@id/postTime" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

  • 你能添加你的布局吗?
  • 我认为您的postListnull 因为您没有分配任何值。使用此Log.e("pastist",Gson().toJson(postList)) 检查帖子列表是否包含数据
  • @Md.Asaduzzaman 我已添加请查看

标签: android kotlin android-recyclerview retrofit


【解决方案1】:

我认为你应该在将适配器设置为 recyclerview 之前定义适配器,像这样交换行。

restAdapter = RestAdapter(postList, restList)
recyclerView?.adapter = restAdapter

【讨论】:

    【解决方案2】:

    您的实施中存在多个问题。检查以下:

    问题 - 1:你没有初始化你restInterface

    restInterface = RestClient.apiService
    val call = restInterface?.getPosts
    

    问题 - 2:从 API 获取后,您没有初始化 postList

    postList = restList?.posts
    

    问题 - 3: 在初始化之前分配适配器时,使用 null 适配器初始化 RecyclerView

    if (response.body() != null) {
        restList = response.body()
        val layoutManager = LinearLayoutManager(applicationContext)
        recyclerView?.layoutManager = layoutManager
    
        // initialize postList with posts
        postList = restList?.posts
        restAdapter = RestAdapter(postList, restList)
    
        //this should be come later
        recyclerView?.adapter = restAdapter
    }
    

    问题 - 4: 在您的 AndroidManifest.xml 中添加 usesCleartextTraffic 以支持 http 请求

    <application
        android:usesCleartextTraffic="true"
        ... >
    

    【讨论】:

    • @sashabeliy,检查解决方案
    • 应用程序仍然显示白屏感谢您的建议我不明白我的代码有什么问题
    • 我已经按照你说的进行了更新,但它仍然显示白屏我正在逐个检查断点
    • 我已经按照你说的添加了
    猜你喜欢
    • 2017-03-15
    • 2015-11-03
    • 2023-01-25
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多