简体   繁体   中英

Retrofit2 with Kotlin

I want to consume an API with this result:

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

It seems the problem is in Kotlin. Here's my code:

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()
            }
        }
    }
}

My variable 'response' always returns 'false' and I want to consume the API value. so 'response' should have a 'true' value. Do you have any suggestion?

Thank you so much!

Your response schema is

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

So, in your response schema, there is only result and status . But in your getResponse() , you assign boolean variable response with res.response . You are using response instead of result .

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

You initialize your response variable with false , your variable response always return false . So you must change the code as follow

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

If my solution is something wrong, please free to know.

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

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM