Skip to content

Instantly share code, notes, and snippets.

@MrFincher
Created March 23, 2021 14:22
Show Gist options
  • Save MrFincher/d5f51112dd5c64c0bc12067c4a3c824a to your computer and use it in GitHub Desktop.
Save MrFincher/d5f51112dd5c64c0bc12067c4a3c824a to your computer and use it in GitHub Desktop.
fun loadData() {
// this is the url where we want to get our data
// Note: 10.0.2.2 is for the Android -emulator, it redirects to your computers localhost!
val JSON_URL = "https://jsonplaceholder.typicode.com/todos/"
// Request a string response from the provided URL.
val stringRequest: StringRequest = object : StringRequest(
Request.Method.GET, JSON_URL,
Response.Listener { response ->
// response from API, you can use this in TextView, for example
// Check also out the example below
// "Handling the JSON in the Volley response" for this part
val gson = GsonBuilder().create();
var rows : ArrayList<TodoItem> = gson.fromJson(response, Array<TodoItem>::class.java).toCollection(ArrayList())
for(item: TodoItem in rows)
{
Log.d("Volley", item.title)
}
recyclerAdapter = RecyclerAdapter(rows)
recyclerView.adapter = recyclerAdapter
// Note: if you send data to API instead, this might not be needed
// Log.d("Volley", response)
},
Response.ErrorListener {
// typically this is a connection error
Log.d("Volley", it.toString())
})
{
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
// we have to specify a proper header, otherwise Apigility will block our queries!
// define we are after JSON data!
val headers = HashMap<String, String>()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json; charset=utf-8"
return headers
}
}
// Add the request to the RequestQueue. This has to be done in both getting and sending new data.
val requestQueue = Volley.newRequestQueue(context)
requestQueue.add(stringRequest)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment