androidkotlinandroid-volley

Android Kotlin: Callback method inside Activity by separeted class?


I have created a class called HttpRequests.kt, Where it stores a simple method responsible for making requests on the internet:

import android.content.Context
import android.util.Log
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley

class HttpRequests() {

    fun doARequest(context: Context){
        val queue = Volley.newRequestQueue(context)
        val url = "https://www.google.com"

        val stringRequest = StringRequest(
            Request.Method.GET, url,
            { response ->
                //How I can call a method inside ConfigActivity file, sending the variable 'response'?
            },
            { error -> Log.d("http","[ERROR]: $error") })

        queue.add(stringRequest)
    }

}

As you can see, I'm using the Volley library to send and receive requests.

This method (doARequest) is called once my ConfigActivity.kt screen is created by the onCreate() method:

class ConfigActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
        //Handle Request
        val requests: HttpRequests = HttpRequests()
        requests.doARequest(this)
    }
}

This code works like a charm. As we know the return methods of the Volley library are asynchronous, in this case, the execution of the code is not affected by the request.

Knowing this, how can I call a callback within the StringRequest response, in order to execute an existing method within my ConfigActivity?

For example: When the request return, I need to call a method that exists inside ConfigActivity, where this method will be responsible for sending the user to the next screen.


Solution

  • I guess you are looking for something like this:

    fun doARequest(context: Context, onResponse:(response: YourType) -> Unit){
    val queue = Volley.newRequestQueue(context)
    val url = "https://www.google.com"
    
    val stringRequest = StringRequest(
        Request.Method.GET, url,
        onResponse,
        { error -> Log.d("http","[ERROR]: $error") })
    
    queue.add(stringRequest)
    }