【问题标题】:Retrofit2 with Kotlin使用 Kotlin 进行改造 2
【发布时间】:2020-02-18 03:28:14
【问题描述】:

我想使用一个带有这个结果的 API:

{"result":true,"status":"success"}

看来问题出在 Kotlin 上。这是我的代码:

class MainActivity : AppCompatActivity() {
private var response:Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    getRetrofit()

    btnLogin.setOnClickListener {

        getResponse()
        Toast.makeText(this,response.toString(),Toast.LENGTH_LONG).show()
    }
}


private fun getRetrofit(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("http://192.168.43.243:2001/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

private fun getResponse() {
    doAsync {
        val call = getRetrofit().create(APIService::class.java).getResponse().execute()
        val res = call.body() as APIResponse
        uiThread {
            if(res.status == "success") {
                response = res.response

            }else{
                //showErrorDialog()
            }
        }
    }
}

我的变量“response”总是返回“false”,我想使用 API 值。所以“响应”应该有一个“真实”的价值。 你有什么建议吗?

非常感谢!

【问题讨论】:

    标签: android kotlin retrofit2


    【解决方案1】:

    您的响应架构是

    { 
      "result":true,
      "status":"success"
    }
    

    因此,在您的响应架构中,只有 result 和 status。但是在您的getResponse() 中,您使用res.response 分配布尔变量响应。您使用的是response 而不是result。

      if(res.status == "success") {
         response = res.response // error here
      }else{
          //showErrorDialog()
      }
    

    你用false初始化你的响应变量,你的变量response总是返回false。 所以你必须改变代码如下

    if(res.status == "success") {
         response = res.result // solved here
      }else{
          //showErrorDialog()
      }
    

    如果我的解决方案有问题,请随时告知。

    【讨论】:

    • Kotlin 不使用== 进行字符串比较,而是使用.compareTo()。
    • @MartinZeitler 我不同意,在 Kotlin 中 a == b 表示 a.equals(b),我认为 String 可以。
    • @MartinZeitler 我认为确实如此。你可以看到kotlin equality
    【解决方案2】:
    // Sample Retrofit 2 Connection Android Using Kotlin
    
    // API Connect On Activity / Fragment
    
            val apiService = ApiMockyClient.clientMocky!!.create(ApiInterface::class.java)
    
                    val call: Call<TimeResponse> = apiService.setTime()
    
                    call.enqueue(object : Callback<TimeResponse> {
                        @SuppressLint("SetTextI18n")
                        override fun onResponse(
                            call: Call<TimeResponse>,
                            response: Response<TimeResponse>
                        ) = when {
                            response.isSuccessful -> {
                                val status = (response.body() as TimeResponse).status
                                val message = (response.body() as TimeResponse).message
    
                                val resultData = response.body()
                                val valGSON = Gson()
                                val valuesStrings = valGSON.toJson(resultData)
    
                                Constant.logD(mTAG, "Fetch Time Response JSON Format : ", valuesStrings)
    
                                when (status) {
                                    "Success" -> {
    
                                        val m24hours = response.body()!!.get24Hours()
    
                                        val m12hours = response.body()!!.get12Hours()
    
                                        Constant.logD(mTAG, "Fetch Employee Response Success : ", "" + message)
                                    }
                                    else -> {
                                        Constant.logE(mTAG, "Fetch Employee Response Failure : ", "" + message)
                                    }
                                }
                            }
                            else -> {
                                Constant.logE(mTAG, "Fetch Time Response : ", "Else Condition !")
                            }
                        }
    
                        override fun onFailure(call: Call<TimeResponse>, t: Throwable) {
                            Constant.logE(mTAG, "Fetch Time Response Failure : ", t.message.toString())
                        }
    
                    })
    
                // Pojo
    
                class TimeResponse(
                @SerializedName("status")
                @Expose var status: String,
                @SerializedName("message")
                @Expose var message: String,
                @SerializedName("24_hours")
                @Expose
                private var _24Hours: List<_24Hour>,
                @SerializedName("12_hours")
                @Expose
                private var _12Hours: List<_12Hour>
            ) {
    
                fun get24Hours(): List<_24Hour> {
                    return _24Hours
                }
    
                fun set24Hours(_24Hours: List<_24Hour>) {
                    this._24Hours = _24Hours
                }
    
                fun get12Hours(): List<_12Hour> {
                    return _12Hours
                }
    
                fun set12Hours(_12Hours: List<_12Hour>) {
                    this._12Hours = _12Hours
                }
    
                override fun equals(other: Any?): Boolean {
                    if (this === other) return true
                    if (javaClass != other?.javaClass) return false
    
                    other as TimeResponse
    
                    if (status != other.status) return false
                    if (message != other.message) return false
                    if (_24Hours != other._24Hours) return false
                    if (_12Hours != other._12Hours) return false
    
                    return true
                }
    
                override fun hashCode(): Int {
                    var result = status.hashCode()
                    result = 31 * result + message.hashCode()
                    result = 31 * result + _24Hours.hashCode()
                    result = 31 * result + _12Hours.hashCode()
                    return result
                }
    
                override fun toString(): String {
                    return "TimeResponse(status=$status, message=$message, _24Hours=$_24Hours, _12Hours=$_12Hours)"
                }
    
    
            }
    
            // API Client 
    
            object ApiMockyClient {
                private var mBaseURLMocky: String = "https://www.mocky.io/v2/"
    
                private var retrofitMocky: Retrofit? = null
    
                val clientMocky: Retrofit?
                    get() {
                        if (retrofitMocky == null) {
                            retrofitMocky =
                                Retrofit.Builder()
                                    .baseUrl(mBaseURLMocky)
                                    .addConverterFactory(GsonConverterFactory.create())
                                    .build()
                        }
                        return retrofitMocky
                    }
    
                init {
                    retrofitMocky = null
                }
            }
    
            // API Interface
            interface ApiInterface {
    
            @GET("5e291efd3000005f00faed17")  // Get Or Post For Example Im Giving 
            fun setTime(): Call<TimeResponse>
    
            }
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2018-08-31
      • 2018-06-13
      • 1970-01-01
      相关资源
      最近更新 更多