Hello,
How to handle an error in volley?
For example I get an error from my api call, what would be the best way to let my fragment know that there is an error. So I don’t go to the next fragment per button click. Now I have a boolean, but I think there is a better option to let my fragment know that an error occurred.
ApiRepository
fun postName(name: String, id: String, callback: (Person) -> (Unit)) {
val json = JSONObject(mapOf(
"name" to name,
"id" to id
))
val req = JsonObjectRequest(Request.Method.POST, "https//example.com", json,
{
val person= Person(it.getString("name"), it.getString("id"), "")
callback(person)
},
{
val person= Person("", "", "", it.toString())
callback(person)
}
)
requestQueue.add(req)
DataClass
data class Person(val name: String, val id: String, val error: String)
MainViewModel
private val name: MutableLiveData<String> = MutableLiveData()
fun getName(): MutableLiveData<String> = name
fun createPerson(): Boolean {
var isError: Boolean = false
name.value?.let {
apiRepository.postName(it, "1234") {
if (it.error.isBlank()) {
id.value = it.id
name.value = it.name
personError.value = it.error
}
if (it.error.isNotBlank()){
personError.value = it.error
isError = true
}
}
}
return isError
}
StartFragment
val btn: Button = binding.buttonStart
btn.setOnClickListener {
if (!mainViewModel.createPerson())
{
navController.navigate(R.id.action_StartFragment_to_PersonFragment)
}
}
Maybe someone has a better solution.
Zeppi