java - 在一项 Activity 中使用 volley 进行两次 API 调用......好的做法?

标签 java android android-volley android-adapter android-glide

我正在获取有关某些神奇宝贝的数据,并且还想获取它们的图像并在同一 Activity 中 Glide 。无法直接获取图像,我必须从 pokemon url 对象中获取图像的 url。

我的意思是我必须首先使用 https://pokeapi.co/api/v2/limit?=10 从响应中获取口袋妖怪 我通过 id https 获取每个口袋妖怪图像 url ://pokeapi.co/api/v2/pokemon/1

我能够在我的适配器中成功地做到这一点,但我想知道这是否是最佳实践,因为我担心如果数字更大它会滞后

适配器在下方

class ApiAdapter (internal var activity: MainActivity):RecyclerView.Adapter<ApiAdapter.ApiViewHolder>(){

    private val queue = Volley.newRequestQueue(activity)


    init{

        loadData()
    }
    val dataInstance = ArrayList<DataClass>()
    private fun loadData(){

        val url = "https://pokeapi.co/api/v2/pokemon?limit=5"

        val jsonObjectRequest = JsonObjectRequest(
            Request.Method.GET, url, null,
            Response.Listener { response ->

                try {
                    val jsonArray = response.getJSONArray("results")
                    lateinit var name:String
                    lateinit var pokeUrl: String
                    lateinit var jsonCities: JSONArray
                    for(i in 0 until jsonArray.length()){
                        val jsonObject = jsonArray.getJSONObject(i)
                        name = jsonObject.getString("name")
                        pokeUrl = jsonObject.getString("url")


                        dataInstance.add(DataClass(name, pokeUrl))

                    }


                    notifyDataSetChanged()

                }
                catch (error: JSONException){
                    error.printStackTrace()
                }


            },
            Response.ErrorListener { error ->
                // TODO: Handle error

                Log.e("Api", "error: $error")

            }

        )
        // Add the request to the RequestQueue.
        queue.add(jsonObjectRequest)
    }




    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ApiViewHolder{
        val layout = LayoutInflater.from(parent.context).inflate(R.layout.data_row, parent, false)
        return ApiViewHolder(layout)
    }

    override fun onBindViewHolder(holder:ApiViewHolder, position:Int){

        val current = dataInstance.get(position)

        holder.name.text = current.name


        fun loadImageData(){

            val url = current.url

            val jsonObjectRequest = JsonObjectRequest(
                Request.Method.GET, url, null,
                Response.Listener { response ->

                    try {
                        val jsonResponse = response.getJSONObject("sprites")
                        val picUrl = jsonResponse.optString("front_default")

                        Glide.with(activity).load(picUrl).into(holder.image)

//                        notifyDataSetChanged()
                        Toast.makeText(activity, "res: $picUrl", Toast.LENGTH_LONG).show()
                    }
                    catch (error: JSONException){
                        error.printStackTrace()
                    }

                },
                Response.ErrorListener { error ->


                    Log.e("Api", "error: $error")

                }

            )
            // Add the request to the RequestQueue.
            queue.add(jsonObjectRequest)
        }

        loadImageData()


    }

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

    class ApiViewHolder(dataView: View): RecyclerView.ViewHolder(dataView){


        internal var name = dataView.findViewById<TextView>(R.id.name)
        internal var image = dataView.findViewById<ImageView>(R.id.pokemon_image)

    }
}

也许有更好的方法来解决这个问题。非常感谢您的建议

最佳答案

一些一般注意事项和建议:

  • 您正在从 onBindViewHolder 触发 API 调用。这将在每次回收后绑定(bind) View 时触发它。您将需要将其从适配器中拉出,或者实现一些缓存。通常,切勿在没有缓存的情况下将 API 放入适配器中,否则会导致灾难。
  • 您正在从适配器内部调用 notifyDatasetChanged()。这通常也被认为是不好的做法。工作流应该是适配器只接收 View 状态数据,然后通过外部 notifyDatasetChanged 将该 View 状态数据应用于它的子级。

不过,对于您的具体情况,您实际上根本不需要额外的 API 调用来获取口袋妖怪的图像。 PokeAPI 中的所有神奇宝贝都使用相同的图像 URL 格式,例如:
https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png

如果您只是将该 URL 中的数字 4 替换为 pokemon 的 ID,就可以避免进行额外的 API 调用,而只需将该手动 URL 直接传递给适配器。然后在完整的详细信息 Activity 或 fragment 中获取完整的口袋妖怪对象。 只是一个想法。

关于java - 在一项 Activity 中使用 volley 进行两次 API 调用......好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866086/

相关文章:

java - 为什么我不能调试 Proxy.newProxyInstance 方法?

android - CWAC 相机 - 连续自动对焦

java - 尝试解析 JSON 数据时出现此错误 W/System.err : org. json.JSONException:对客户没有值(value)

php - 获取无效状态行 10380HTTP/1.1 200 OK

android - 如何知道 Android 操作栏的操作图标是在顶部栏还是底部栏(拆分)?

android - 如何在 Volley 中获取 JSONObject 服务器响应

java 。确定两个方法调用具有相似的线程上下文

c# - 检测用户是否输入假名的服务或策略?

java - 在多模块 Maven 项目中更新模块版本的最佳策略是什么

android - 如何有效地将流式数据从服务传递到 Activity ?