I am new to programming and I need your help. The task is this: I make a request from the service where I want to get the character's id, but it doesn't work. Below is the code!
Api
@GET("people/{id}")
suspend fun getCharacter(@Path("id") id: Int): Response<Characters>
Repository
suspend fun getCharacters(id: Int) =
RetrofitBuilder.api.getCharacter(id)
Viewmodel
class DetailViewModel : ViewModel() {
var repository = StarWarsRepository()
private val _response = MutableLiveData<Characters>()
val character: LiveData<Characters>
get() = _response
fun getCharacter(id: Int) {
viewModelScope.launch {
repository.getCharacters(id).let { response ->
if (response.isSuccessful) {
_response.postValue(response.body())
} else {
Log.d("tag", "Error: ${response.code()}")
}
}
}
}
}
Fragment In line 27 I call the function getCharacterViewModel() and there you need to specify id. What do I need to specify in this parameter so that when I click on a character in the list, I have information about him?
class DetailFragment : Fragment() {
private var _binding: FragmentDetailBinding? = null
private val binding get() = _binding!!
private lateinit var viewModel: DetailViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentDetailBinding.inflate(inflater, container, false)
val view = binding.root
viewModel = ViewModelProvider(this)[(DetailViewModel::class.java)]
getCharacterViewModel()
return view
}
private fun getCharacterViewModel(id: Int){
viewModel.getCharacter(id)
viewModel.character.observe(this, { name ->
binding.birth.text = name.birth_year
binding.name.text = name.characters
binding.mass.text = name.mass
binding.mass.text = name.height
})
}
}