API Request with Volley - jorgepascoPE/Kotlin-snippets GitHub Wiki

Setting up the project to work with Volley

To use Volley for API requests, you must assign permissions to the app to access the internet. In AndroidManifest.xml, inside of the manifest tag, include the next line:

<uses-permission android:name="android.permission.INTERNET"/>

You should also include Volley in your dependencies

dependencies {
    implementation 'com.android.volley:volley:1.1.0'
}

When using internet in an Android Studio device emulator, the BASE URL that references a localhost should be set to "10.0.2.2". So, if you are using port 3005 to host your application, your base url should look like this:

http://10.0.2.2:3005/

To see detailed information of Android Emulator Network, visit the Official Documentation.

POST Request

    fun registerUser(email: String, password: String, complete: (Boolean) -> Unit) {

        val jsonBody = JSONObject()
        jsonBody.put("email", email)
        jsonBody.put("password", password)
        val requestBody = jsonBody.toString()

        val registerRequest = object : StringRequest(Method.POST, URL_REGISTER, Response.Listener { response ->
            complete(true)
        }, Response.ErrorListener { error ->
            Log.d("ERROR", "Could not register user: $error")
            complete(false)
        }) {
            override fun getBodyContentType(): String {
                return "application/json; charset=utf-8"
            }

            override fun getBody(): ByteArray {
                return requestBody.toByteArray()
            }
        }

    Volley.newRequestQueue(context).add(registerRequest)
}

GET Request

fun getFoo(fooParameter: String, complete: (Boolean) -> Unit) {

      //for arrays
      val fooRequest = object: JsonArrayRequest(Method.GET,"${GET_FOO_URL}/?foo=$fooParameter", null, Response.Listener { response ->
          try{
              for (x in 0 until response.length()) {
                  val responseObject = response.getJSONObject(x)
                  val someAttribute = responseObject.getString("key")
                  //do something
              }
              complete(true)
          }catch (e: JSONException) {
              Log.d("JSON", "EXC: ${e.localizedMessage}")
              complete(false)
          }
      }, Response.ErrorListener {
          Log.d("ERROR", "Could not ...")
          complete(false)
      }) {
          override fun getBodyContentType(): String {
              return "application/json; charset=utf-8"
          }

          override fun getHeaders(): MutableMap<String, String> {
              val headers = HashMap<String, String>()
              headers.put("Authorization", "fooToken")
              return headers
          }
      }

      Volley.newRequestQueue(context).add(fooRequest)
}

Recommended to use a unique request queue (Volley.newRequestQueue(context)), and host it in a singleton (or Application class)