【问题标题】:Passing data from activity to interface将数据从活动传递到接口
【发布时间】: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


【解决方案1】:

试试这个:

interface RequestApi {
    @GET("statistiche/{id}")
     fun getAllPosts(@Query("id") id:String): Call<ExchangeResponse>
 }

用法:

// receiving class
String id = intent.getStringExtra("Username")

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(id) // pass id here

【讨论】:

  • 感谢您的回复 Birju。当我添加此代码时,我在调用 getAllPosts 时收到错误,我不明白我需要在哪里插入从其他类收到的参数。我将更新我的问题以添加解释这两个问题的代码。
  • 感谢您帮助我。我继续收到错误,我会更新我的问题以便更好地理解
  • 是的...您可以将其标记为正确它解决了您的问题。
  • 对不起,我还不能运行它,我仍然需要你的帮助
猜你喜欢
  • 2016-05-26
  • 2015-04-21
  • 2016-09-04
  • 2011-02-11
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
相关资源
最近更新 更多