将变量传递给接口

时间:2019-05-08 23:37:14

标签: android json kotlin retrofit2

尝试将设备ID传递到界面,但我什么也没得到。我本质上想将设备ID存储到一个变量中,并将其放在接口的@Get中。

我尝试使用@Path,但对它的使用并不熟悉。

URL在通话中必须看起来像这样

http://xxx.xx.xxx.xxx/apps/api/109/devices/65?access_token=xxxxxx

接口

interface DeviceDetailsAPIClient {

    @GET("devices/<item id here>")
    fun getDevicesDetailsAsync(@Query("access_token") access_token: String): Deferred<Response<DeviceDetails>>
}

将ID传递到的MainActivity2

class MainActivity2 : AppCompatActivity() {
    private val tag : String = MainActivity2::class.java.simpleName
    var deviceID: String = intent.getStringExtra("deviceID")
    private lateinit var adapterDetails: DeviceDetailsAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        rv_devices.layoutManager = LinearLayoutManager(this)
        rv_devices.hasFixedSize()
        adapterDetails = DeviceDetailsAdapter(listOf()) { deviceDetails: DeviceDetails -> deviceDetails }
        rv_devices.adapter = adapterDetails
        loadDeviceDetails()
    }

        private fun loadDeviceDetails() {
            GlobalScope.launch(Dispatchers.Main) {
                try {
                    val webResponseDetails = deviceDetailsApi.getDevicesDetailsAsync(access_token = "xxxxxx").await()
                    if (webResponseDetails.isSuccessful) {
                        val deviceDetails: DeviceDetails? = webResponseDetails.body()
                        Log.d(tag, deviceDetails?.toString())
                        //adapterDetails.deviceDetails = deviceDetails ?: listOf()
                        adapterDetails.notifyDataSetChanged()
                    } else {
                        Log.e(tag, "Error ${webResponseDetails.code()}")
                        Toast.makeText(this@MainActivity2, "Error ${webResponseDetails.code()}", Toast.LENGTH_LONG).show()
                    }
                } catch (e: IOException) {
                    Log.e(tag, "Exception " + e.printStackTrace())
                    Toast.makeText(this@MainActivity2, "Exception ${e.message}", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

这是我将ID存储在其中的变量

var deviceID: String = intent.getStringExtra("deviceID")

现在如何将其显示到界面上?

1 个答案:

答案 0 :(得分:0)

@Path批注可用于更改URL:

interface DeviceDetailsAPIClient {

    @GET("devices/{deviceId}")
    fun getDevicesDetailsAsync(
        @Path("deviceId") deviceId: Long,
        @Query("access_token") access_token: String
    ): Deferred<Response<DeviceDetails>>
}