Ciao a tutti
sto provando a richiamare delle api tramite Retrofil,
con il contenuto voglio riempire un listview.
Tutto mi riesce se riempio direttamente all'interno de onResponse la lista, se invece dalla classe dove ho la lista richiamo con una funzione la chiamata Retrofil la lista non si riempi
Vi posto il codice
all'interno di onCreate di ListView.kt ho
codice:
var listOfPosts = ArrayList<Client>()
doAsync {
val requestApi : ClientList = ApiService().GetClients(urlConnection, authTokenBearer) as ClientList
var listJson = requestApi.clientList ?: emptyList()
//// ScrollView
for (_client in listJson) {
listOfPosts.add(
Client(
_client.numero,
_client.denomination,
_client.typeClient,
_client.id
)
)
}
var myUsersAdapter = PostsAdater( context ,listOfPosts)
listUsers.adapter= myUsersAdapter
}
mentre nella classe ApiService ho questo
codice:
fun GetClients(urlConnection: String, authToken: String) : Any? {
val clientBuilder = OkHttpClient.Builder()
///token Bearer
val authTokenBearer = "Bearer " + authToken
//Create a new Interceptor.
val headerAuthorizationInterceptor: Interceptor = object : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): okhttp3.Response? {
val original = chain.request()
val request = original.newBuilder()
.header("Authorization", authTokenBearer)
.method(original.method(), original.body())
.build()
return chain.proceed(request)
}
}
//Add the interceptor to the client builder.
clientBuilder.addInterceptor(headerAuthorizationInterceptor)
val client: OkHttpClient = clientBuilder.build()
var retrofit = Retrofit.Builder()
.baseUrl(urlConnection)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
val jsonApi = retrofit.create(ClientApiJson::class.java)
val call = jsonApi.getClients()
var bodyResponse: Any? = null
//JsonElement
call.enqueue(object : Callback<ClientList> {
override fun onResponse(call: Call<ClientList>, response: Response<ClientList>) {
if (!response.isSuccessful) {
Log.d("Error", " getClients !response.isSuccessful")
return
}
val body = response.body()!!
var listBody = response?.body()?.clientList ?: emptyList()
bodyResponse = body
}
override fun onFailure(call: Call<ClientList>, t: Throwable) {
Log.d("Error", t.message)
}
})
return bodyResponse
}
}
Io ho aggiunto alla fine bodyResponse, ma credo che debba andare onResponse
Credevo che doAsync attendeva la risposta della funzione per poter riempire la lista.
Potete darmi qualche suggerimento
Grazie