【发布时间】:2019-07-16 18:06:11
【问题描述】:
我正在尝试将我的数据从一项活动传递到 kotlin 中的接口。这个值必须组成一个获取请求 json 的 url。可能吗?我该怎么做?
我是应用程序开发的新手,以前从未使用过接口。
package com.example.adamo3.Request
import com.example.adamo3.Response.ExchangeResponse
import retrofit2.Call
import retrofit2.http.GET
interface RequestApi {
@GET("statistiche/09050905")
fun getAllPosts(): Call<ExchangeResponse>
}
我的目标是通过将“09050905”更改为我在一个活动中创建的参数来修改此网址“statistiche/09050905”。这样,我将更改 url 以从我的服务器调用。
更新 1)我试图插入
interface RequestApi {
@GET("statistiche/{id}")
fun getAllPosts(@Query("id") id: String ): Call<ExchangeResponse>
}
但是当我这样做时,当我从一个类(这个)调用 getAllPosts 时收到错误
private val retrofit =
Retrofit.Builder().baseUrl("http://x.x.x.x:xxxx/")
.addConverterFactory(GsonConverterFactory.create())
.build()
private val postApi=retrofit.create(RequestApi::class.java)
private val response = postApi.getAllPosts()// i receive error here
2)为了检索我需要的值,在我使用的其他类中
// receiving class
textView.text = intent.getStringExtra("Username")
// sending class
val intent = Intent(this@MainActivity,Home::class.java)
intent.putExtra("Username" ,"ID " + editText.text.toString())
startActivity(intent)
我需要在哪里定义这部分到界面代码建议我?我需要editText中的值到达界面
3) 我需要在哪里定义带有意图的字符串?如果我在界面中这样做,“界面中不允许使用属性初始化器”
interface RequestApi {
@GET("statistiche/{id}")
fun getAllPosts(@Query("id") id: String ): Call<ExchangeResponse>
String id = intent.getStringExtra("Username")//these two ways are errors
var id = intent.getStringExtra("Username")//same error
}
我想在接口内接收值
4) 如果我在这里添加 id,它仍然是红色的错误
private val response = postApi.getAllPosts(id)//id is red
【问题讨论】:
-
如果对您有用,请将答案标记为正确!
标签: android-studio kotlin parameter-passing retrofit