如何从MainActivity转移字符串到单个对象?



我有ServiceBuilder对象

object ServiceBuilder {
//private var url: String? = null
var url = "http://no-google.com"    // The default link
fun loadUrl(url: String): ServiceBuilder{
this.url = url
return this
}
private var logger = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
val headerInterceptor = object: Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
request = request.newBuilder()
.addHeader("x-device-type", Build.DEVICE)
.addHeader("Accept-Language", Locale.getDefault().language)
.build()
val response = chain.proceed(request)
return response
}
}
// Create OkHttp Client
private val okHttp = OkHttpClient.Builder()
.callTimeout(5, TimeUnit.SECONDS)
.addInterceptor(headerInterceptor)
.addInterceptor(logger)
// Create Retrofit Builder
private val builder = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttp.build())
// Create Retrofit Instance
private val retrofit = builder.build()
fun <T> buildService(serviceType: Class<T>): T {
return retrofit.create(serviceType)
}
}

getUrlFromServer ()MainActivity

private fun getUrlFromServer(str: String){
val destinationService = ServiceBuilder
.loadUrl("http://google.com")       // <-- This call can not reply url into ServiceBuilder object
.buildService(DestinationService::class.java)
val requestCall = destinationService.getList()
requestCall.enqueue(object: Callback<List<Destination>> {
override fun onResponse(
call: Call<List<Destination>>,
response: Response<List<Destination>>
) {
if (response.isSuccessful){
val destinationList = response.body()
//Toast.makeText(this, destinationList.toString(), Toast.LENGTH_LONG)
}
}
override fun onFailure(call: Call<List<Destination>>, t: Throwable) {
TODO("Not yet implemented")
}
})
}

我不明白为什么loadUrl()ServiceBuilder内部的函数无法加载url。我需要从MainActivity发送url到ServiceBuilder对象。

请告诉我如何以良好的风格来决定这个问题

因为创建retrofit实例,需要在ServiceBuilder loadUrl函数之前执行。实际改装实例,总是用"http://no-google.com"网址! !

fun <T> buildService(serviceType: Class<T>): T {
// Create Retrofit Builder
private val builder = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttp.build())
// Create Retrofit Instance
private val retrofit = builder.build()
return retrofit.create(serviceType)
}

相关内容

  • 没有找到相关文章

最新更新