Skip to content

08 - Android RESt api's

Using REST apis - Volley

Add library for Volley

1
2
3
4
dependencies {
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.android.volley:volley:1.2.1'
}

Singleton for handling requests

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import android.content.Context
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.Volley

class HttpSingletonHandler(context: Context) {
    companion object {
        private val TAG = HttpSingletonHandler::class.java.simpleName

        @Volatile
        private var INSTANCE: HttpSingletonHandler? = null

        fun getInstance(context: Context) =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: HttpSingletonHandler(context).also {
                    INSTANCE = it
                }
            }
    }

    val requestQueue: RequestQueue by lazy {
        // applicationContext is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        Volley.newRequestQueue(context.applicationContext)
    }

    fun <T> addToRequestQueue(req: Request<T>) {
        req.tag = TAG
        requestQueue.add(req)
    }

    fun cancelPendingRequests(tag: Any) {
        if (requestQueue != null) {
            requestQueue.cancelAll(tag)
        }
    }
}

Request

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    fun onClickregister(view: android.view.View) {
        var url = "https://sportmap.akaver.com/api/v1/Account/Register"
        var handler = HttpSingletonHandler.getInstance(this)

        var httpRequest = object : StringRequest(
            Request.Method.POST,
            url,
            Response.Listener { response -> Log.d("Response.Listener", response) },
            Response.ErrorListener { error ->  Log.d("Response.ErrorListener", "${error.message} ${error.networkResponse.statusCode}")}
        ){
            override fun getBodyContentType(): String {
                return "application/json"
            }

            override fun getBody(): ByteArray {
                val params = HashMap<String, String>()
                params["email"] = "user123456789@user.ee"
                params["password"] = "Foo.bar.1"
                params["firstName"] = "firstName"
                params["lastName"] = "lastName"

                var body = JSONObject(params as Map<*, *>).toString()
                Log.d("getBody", body)

                return body.toByteArray()
            }
        }

        handler.addToRequestQueue(httpRequest)
    }