I developed an Android app using Kotlin and all the structure and functionality are complete, but I noticed a small issue when I tap fast repeatedly, at least twice on a button that does an API call.
For the API calls I am using a combination of RetroFit2 and GsonConverterFactory. The call is as follows:
fun fetchInfo(id: Int) {
val retrofit = Retrofit.Builder()
.baseUrl("https://www.mysitesurl.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiService::class.java)
api.getInfo(id).enqueue(object: Callback<DataType> {
override fun onResponse(call: Call<DataType>, response: Response<DataType>) {
var resp = response.body()!!
my_image.setImageResource(resources.getIdentifier(resp.image, "drawable", context!!.packageName))
my_image.visibility = View.VISIBLE
my_label.text = resp.text
my_label.visibility = View.VISIBLE
}
override fun onFailure(call: Call<FechaDia>, t: Throwable) {
}
})
}
I have edited the code a bit to avoid specific variable names
So, as mentioned before this code works fine, the problem comes when I click the navigation button twice fast. From what I understand it tries to make another API call before the current one has responded and gets a null response, so I basically try to substitute an image with a null resource and it shows me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference`
I tried using try/catch but it still makes the call and still receives a null request. Is there a way to block this from happening or what am I missing in my process here?
The main issue is that it doesn't just show an error, the app closes and shows the App has stopped. Open app again
message.