[EDIT]
Estaba desarrollando una App enAndroid, en la que he intentado implementar una llamada a un endpoint de una api concreta, y lo he intentado hacer con la libreria de Retrofit.
El endpoint que estoy intentando consumir es el siguiente:
https://hello-world.innocv.com/api/User/
El tema, es que al hacer la llamada,al principio no me llegaba nada, y ahora tras hacer unas modificaciones recibo el siguiente error:
java.langIllegalException: UNable to create call Adapter for retrofit2.Response<java.util.List<>UserElement>>
....
....
El fragment donde realizo la llamada es el siguiente:
class MainFragment : Fragment(), SearchView.OnQueryTextListener {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var recyclerView: RecyclerView
private lateinit var layoutManager: RecyclerView.LayoutManager
private lateinit var recycleAdapter: UserAdapter
private var userElements = mutableListOf<UserElement>()
private lateinit var userById: UserElement
private lateinit var btnAdd: SearchView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
var root: View = inflater.inflate(R.layout.main_fragment, container, false)
/*
viewModel.users?.observe(viewLifecycleOwner){
//TODO:Update the View
}
*/
//Inicializo la vista y levanto el RecycleView.
initView(root)
initRecycle()
return inflater.inflate(R.layout.main_fragment, container, false)
}
private fun initRecycle() {
layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL, false)
recyclerView.setLayoutManager(layoutManager)
recycleAdapter = UserAdapter(context, userElements)
recyclerView.adapter = recycleAdapter
}
private fun initView(root: View) {
//Set the visibility to invisible until, the user do the request.
val progressBar = root?.findViewById<ProgressBar>(R.id.progressBar)
progressBar?.visibility ?: View.INVISIBLE
//Inicializo el Search, y le agrego el listener.
btnAdd = root.findViewById(R.id.btnAdd)
btnAdd.setOnQueryTextListener(this)
recyclerView = root.findViewById(R.id.recycleview)
//Cargo el Array con los Usuarios de la API
loadAllUsers()
val btnAdd= root?.findViewById<SearchView>(R.id.btnAdd)
btnAdd?.setOnClickListener() {
progressBar?.visibility = View.VISIBLE
btnAdd?.visibility = View.INVISIBLE
//TODO("Implementar llamada a la API con Retrofit")
val args: String = btnAdd.query as String
userById = searchUserById(args)
if (userById!=null) {
userElements.clear()
userElements.add(userById)
recycleAdapter.notifyDataSetChanged()
}
}
//Si lo llamo aqui explota.
//HttpUrl.parse("https://hello-world.innocv.com/api/User/")?.let { loadAllUsers(it) }
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
//viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
}
private fun getRetrofit():Retrofit{
return Retrofit.Builder()
.baseUrl("https://hello-world.innocv.com/api/User/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private fun searchUserById(uid:String): UserElement{
CoroutineScope(Dispatchers.IO).launch {
val call:Response<UserElement> = getRetrofit().create(ApiService::class.java).getUsersById(
uid
)
val user: UserElement? = call.body()
activity?.runOnUiThread{
if(call.isSuccessful){
user?.let { userElements.add(it) }
}else{
Toast.makeText(context, "No se ha encontrado ningun usuario", Toast.LENGTH_LONG).show()
}
}
}
//Retorno el unico usuario que deberia haber con el id seleccionado.
return userElements[0]
}
private fun loadAllUsers(): List<UserElement>{
CoroutineScope(Dispatchers.IO).launch {
//TODO: Puede que tenga que añadirle '/id' a call
val call:Response<List<UserElement>> = getRetrofit().create(ApiService::class.java).getUsers(
)
val users: List<UserElement>? = call.body()
activity?.runOnUiThread {
if(call.isSuccessful){
//show RecycleView
val userscall: ArrayList<UserElement> = arrayListOf()
for (input: UserElement in users!!) {
userscall.add(input)
}
userElements.clear()
userElements.addAll(userscall)
recycleAdapter.notifyDataSetChanged()
}else{
//Show error
showError()
}
}
}
return userElements
}
private fun showError() {
Toast.makeText(context, "Se ha producido un error", Toast.LENGTH_LONG).show()
}
override fun onQueryTextSubmit(query: String?): Boolean {
if(!query.isNullOrEmpty()){
//Cargamos los usuarios que haya en la API
HttpUrl.parse("https://hello-world.innocv.com/api/User/")?.let { loadAllUsers() }
}
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
return true
}
}
Mi ApiService.kt, seria el siguiente:
interface ApiService {
@GET("/User/")
fun getUsers():Response<List<UserElement>>
@GET(value = "/User/" + "\$uid")
fun getUsersById(uid: String):Response<UserElement>
}
Y finalmente el Adapter del RecycleView donde trato de pintar los datos sería el siguiente:
UserAdapter.kt
class UserAdapter(val context: Context?, var userList: List<UserElement>) : RecyclerView.Adapter<UserAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user_layout,parent,false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return userList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.txtName.text = userList.get(position).name
holder.txtBirthday.text = userList.get(position).birthday
}
fun setUserListItems(userList: List<UserElement>){
this.userList = userList;
notifyDataSetChanged()
}
class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
val txtName: TextView = itemView!!.findViewById(R.id.name)
val txtBirthday: TextView = itemView!!.findViewById(R.id.birthday)
}
}
Con respecto a la clase que uso como data class es la siguiente:
data class UserElement(
@SerializedName("name") var name: String,
@SerializedName("birthday") var birthday: String,
@SerializedName("id") var id: Int)
Si pueden ayudar muchas gracias de ante mano, y reciban un saludo!