简体   繁体   中英

How to handle retrofit response Kotlin in android?

All of you. I am doing sample Android Kotlin Project from api call using retrofit. I called api and display response logcat. But it is not handling the user id and data to from server. So, If you know Guys share your best experience.

  val params = HashMap<String, String>()
    params["api_key"] = "api_key_value"
    params["username"] = "abcd"
    params["password"] = "1234"

    doApiLogin.getLogin(params).enqueue(object : Callback<GetLoginAndRegisterResp> {

        override fun onResponse(call: Call<GetLoginAndRegisterResp>?, response: Response<GetLoginAndRegisterResp>?) {
            //To change body of created functions use File | Settings | File Templates.
            if (response != null && response.isSuccessful) {

                val getLoginAndRegisterResp = response.body()
                if (getLoginAndRegisterResp != null) {

                    // Here. server response

                } else {

                    val statusCode = response.code()
                    NajibApplication.instance.setLog("statusCode:" + statusCode)
                }


            } else {
                NajibApplication.instance.setLog("onFailure>>>>")
            }
        }

        override fun onFailure(call: Call<GetLoginAndRegisterResp>?, t: Throwable?) {
            //To change body of created functions use File | Settings | File Templates.
            NajibApplication.instance.setLog("onFailure>>>>")
        }

    })

Here is Model Class

class GetLoginAndRegisterResp {

data class LoginResp(
        val user_info: UserInfo = UserInfo(),
        val status: Status = Status()

) {
    override fun toString(): String {
        return "LoginResp(user_info=$user_info, status=$status)"
    }
}

data class UserInfo(
        @SerializedName("user_id")
        val user_id: String = "", //

        @SerializedName("username")
        val username: String = "", //abcd

        @SerializedName("login_hash")
        val login_hash: String = "", //

        @SerializedName("facebook_id")
        val facebook_id: String = "",

        @SerializedName("twitter_id")
        val twitter_id: String = "",

        @SerializedName("full_name")
        val full_name: String = "", //

        @SerializedName("thumb_url")
        val thumb_url: String = "",

        @SerializedName("photo_url")
        val photo_url: String = "",

        @SerializedName("mobile")
        val mobile: String = "", //

        @SerializedName("email")
        val email: String = "" //
) {
    override fun toString(): String {
        return "UserInfo(user_id='$user_id', username='$username', login_hash='$login_hash', facebook_id='$facebook_id', twitter_id='$twitter_id', full_name='$full_name', thumb_url='$thumb_url', photo_url='$photo_url', mobile='$mobile', email='$email')"
    }
}

data class Status(
        @SerializedName("status_code")
        val status_code: String = "", //-1

        @SerializedName("status_text")
        val status_text: String = "" //Success.
) {
    override fun toString(): String {
        return "Status(status_code='$status_code', status_text='$status_text')"
    }
}

}

This is code here with Api calling retrofit Kotlin.

import com.google.gson.GsonBuilder

import java.util.concurrent.TimeUnit

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object APIClient {

    private var retrofit: Retrofit? = null

    val client: Retrofit
        get() {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            val client = OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .connectTimeout(1, TimeUnit.MINUTES)
                    .retryOnConnectionFailure(true)
                    .build()
            if (retrofit == null) {
                val gson = GsonBuilder()
                        .setLenient()
                        .create()

                retrofit = Retrofit.Builder()
                        .baseUrl("")
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client)
                        .build()


            }
            return this!!.retrofit!!

        }

}



interface APIInterface {

    @POST("login")
    fun callLoginWebservice(@Query("device_token") token: String,
                            @Query("email") userName: String,
                            @Query("password") password: String

    ): Call<UserLoginDetailModel>}

in your class :

  init {
        if (apiInterface == null) {
            apiInterface = APIClient.client.create(APIInterface::class.java)
        }
    }
  apiInterface?.callLoginWebservice(token, userName, password).enqueue(object : Callback<UserLoginDetailModel> {
            override fun onResponse(call: Call<UserLoginDetailModel>, response: Response<UserLoginDetailModel>) {

                loginResponseInterface.onSuccess(loginDetail?.status.toString(),loginDetail ?. errorcode.toString(), loginDetail)
                Log.d("WebServices", "" + loginDetail)

            }

            override fun onFailure(call: Call<UserLoginDetailModel>, t: Throwable) {
                // loginResponseInterface.onSuccess("","", loginDetail);
                loginResponseInterface.onFailure(t)
            }
        })

Your bean :

class UserLoginDetailModel {
    @SerializedName("_id")
    @Expose
    var id: String? = null


    @SerializedName("email")
    @Expose
    var email: String? = ""

    @SerializedName("name")
    @Expose
    var name: String? = null

    @SerializedName("height_value")
    @Expose
    var heightValue: String? = "0'0''"}

A lot of search and found solution on my self. Solution as model class is not perfect and this is correct model class as our requirement.

  1. Create file as Kotlin only.
  2. Convert Json Into Kotlin Class.

And clear project and run! :)

It should be work fine!

data class LoginResultResp(
    val user_info: UserInfo = UserInfo(),
    val status: Status = Status())

data class UserInfo(
    val user_id: String = "", //1010
    val username: String = "", 
    val login_hash: String = "", 
    val facebook_id: String = "",
    val twitter_id: String = "",
    val full_name: String = "", //
    val thumb_url: String = "",
    val photo_url: String = "",
    val mobile: String = "", //
    val email: String = "")

data class Status(
    val status_code: String = "", //-1
    val status_text: String = "" //Success.)

This is how I use the Response class, and it's very useful for me.

sealed class Response<out T> {
object Loading: Response<Nothing>()

data class Success<out T>(val data: T): Response<T>()

data class Error(val message: String): Response<Nothing>()

}

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