Volley in Android

Overview

Volley is a HTTP Library that is used in Android applications. It is used to make networking tasks easier and most importantly faster. With Volley all you have to do is add your request in a RequestQueue and you will get your response parsed and delivered in the form of Response Listener  if everything is fine or else Response Error Listener.

Steps to follow

  • Add the following dependency
 def volley_version = "1.2.1"
implementation "com.android.volley:volley:$volley_version"
  • Add Internet permission in AndroidManifest.xml file
 <uses-permission android:name="android.permission.INTERNET" />
  • For a Simple String Request
 class MainActivity : AppCompatActivity() {
companion object {
const val SERVER_URL = "https://jsonplaceholder.typicode.com/posts/1"
}

private lateinit var requestQueue: RequestQueue
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestQueue = Volley.newRequestQueue(this)
}

override fun onStart() {
btnShow.setOnClickListener {
val stringRequest =
StringRequest(Request.Method.GET, SERVER_URL, { response ->
txtLabel.text = response.substring(0, 50)
}, { error ->
txtLabel.text = error.toString()
})
requestQueue.add(stringRequest)
}
super.onStart()
}

}
  • For a JSON Request
 class MainActivity : AppCompatActivity() {
companion object {
const val SERVER_URL = "https://jsonplaceholder.typicode.com/posts/1"
}

private lateinit var requestQueue: RequestQueue
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestQueue = Volley.newRequestQueue(this)
}

override fun onStart() {
initViews()
super.onStart()
}

private fun initViews() {
/* As it is a GET Request, you can pass null for JSON Request*/
btnShowJSON.setOnClickListener {
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, SERVER_URL, null, {
txtLabel.text = it.toString().substring(0, 50)
}, {
txtLabel.text = it.stackTraceToString()
})
requestQueue.add(jsonObjectRequest)
}
}
}
  • Hello World

Do's and Dont's

  • Volley is not suitable for large downloads and streaming operations because Volley holds all responses in memory during parsing.

Reference



Comments

Popular posts from this blog

SSLSocketFactory in Android

Architecture Components in Android

DataBinding in Android